Function in Jquery passing form element's ID as parameter

27,427

Remove the quotes from around the parameter, and concatenate a # to the beginning of it.

$('#' + ID).html(output);

$('#' + ID).removeAttr('disabled');

Also, this will likely reference the window instead of whatever element you expect, so the following won't work:

{operator:$(this).val()}

If it should reference the select element, then add this as a second argument:

onchange=getOffice(sender,this)

...and reference it with a parameter:

function getOffice(ID, el){
    $.post('dynamicOffice.php',{operator:$(el).val()},function(output){
        $('#' + ID).html(output);
    });
    $('#' + ID).removeAttr('disabled');
}
Share:
27,427
Admin
Author by

Admin

Updated on December 24, 2020

Comments

  • Admin
    Admin over 3 years

    I'm trying to make a function in Jquery that will take the ID of form SELECT element's ID where a dynamically created option should be displayed. But, i have to repeat this work for other form instances as well. i have created the following code, but it did not work.

    JQuery Script

    function getOffice(ID){
        $.post('dynamicOffice.php',{operator:$(this).val()},function(output){
        $('ID').html(output);
        });
            $('ID').removeAttr('disabled');
    }
    

    Main HTML File

    <select id="senderOperator" name="senderOperator" tabindex="1" onchange=getOffice(sender)>
        <option value=""><--SELECT an Operator --></option>                 
            <?php getOption($operator,Operator) ?>
    </select>
    
    <select id="sender" name="sender" tabindex="1" disabled="disabled">
        <option value=""><--SELECT the Operator First --></option>
    </select>
    

    dynamicOffice.php

    <?php
    include('generateOption.php');
        $country=$_POST['operator'];
        $officeSql="SELECT * FROM myoffice WHERE Operator='$country'";
        getOption($officeSql,Name);
    ?>
    

    generateFormElement.php

    <?php
    include("include/dbConnect.php");       
    
    function getOption($rsSql,$colName){
    
        $sResult=mysql_query($rsSql) or die("Could Not Fetch Records");
    
        while ($s_Office = mysql_fetch_array($sResult))
        {
            echo("<option value='".$s_Office["$colName"]."'>".$s_Office["$colName"]."</option>");
        }
    }
    ?>
    
  • Sikshya Maharjan
    Sikshya Maharjan almost 13 years
    Ugh, answer the question first, and then edit the question...sigh. When will I learn..? =/
  • Sikshya Maharjan
    Sikshya Maharjan almost 13 years
    Actually, +1 because I forgot to remove the quotes from around the variable, too. Sigh...and the rest of your answer made yours better than mine was likely to be. =D
  • Raynos
    Raynos almost 13 years
    @DavidThomas I had the exact same thing. I was editing the question, but you beat me to the question edit too!