简体   繁体   中英

How to call javascript or jquery function inside dropdown

I have the following HTML code:

<select name = 'category' id='category'>
    <option value="a">A <a href="" class = "edit" id ='1'> Click here to edit </a> </option>
    <option value="b">B <a href="" class = "edit" id ='b'> Click here to edit </a> </option>
</select> 

I am trying like this:

$(document).on('click','.edit', editfunction);

function editfunction() {
    alert('hi');
    //call here ajax code 
}

Firstly your HTML is invalid; you cannot have a elements inside an option :

<select name="category" id="category">
    <option value="a">A</option>
    <option value="b">B</option>
</select>

To do what you require you can hook to the change event of the select , not the click of the a within the option . You can then use $(this).val() to get the selected value in editFunction() :

$(document).on('change', '#category', editfunction);

function editfunction() {
    var value = $(this).val();
    console.log(value);
    // AJAX...
}

Try using the following

$('#category').on('change', function(){
   editfunction( $(this).val() );
 })

function editfunction(val){
   // Make your ajax call here
}

And You actually dont need the tag inside to make this happen

I think this is what u want JSFIDDLE example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM