简体   繁体   中英

How can I call a jquery function on selecting a dropdown option for dynamically created inputs?

So this is what the page looks like currently:

在此处输入图片说明

The first one is hardcoded in and then the rest are added/removed by the buttons. The first one can also be added and removed from the buttons. I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc.

Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. I'm not sure why that is.

Here is how the Q/A's are created and removed

$("#addButton").click(function () {

    if (counter > max_fields) {
        alert("Only " + max_fields + " Questions allowed");
        return false;
    }

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
          '<input type="text" name="textbox' + counter +
          '" id="questionbox' + counter + '" value="" />' +
          ' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
          '<button id = "remove' + counter + '">Remove</button>' +
          '<br/><label>Answer #' + counter + ' : </label>' +
          '<div id="Answers' + counter + '">' +
          'Option 1: <input type="text" id="answerbox' + counter +
          '1" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 2: <input type="text" id="answerbox' + counter +
          '2" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 3: <input type="text" id="answerbox' + counter +
          '3" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 4: <input type="text" id="answerbox' + counter +
          '4" name="answerbox' + counter + '" value="" /></div>');

    newTextBoxDiv.appendTo("#TextBoxesGroup");
    counter++;
});

$("#removeButton").click(function () {
    if (counter == 1) {
        alert("No more textbox to remove");
        return false;
    }
    counter--;
    $("#TextBoxDiv" + counter).remove();
});

This is how I tried to get it to change types

$('#choice1').change(function () {
    var selected_item = $(this).val()
    var searchEles = document.getElementById("Answers1").children;
    alert(searchEles.length);
    for(var i = 0; i < searchEles.length; i++) {
        $('#answerbox1' + i).attr('type', selected_item);
        //alert(searchEles.length);
    }

});

The web page code is as follows

<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
        <label>Question #1 : </label>
        <input type='text' id='questionbox1'/> 
        <select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
            <option value="">Type</option>
            <option value="radio">Radio Button</option>
            <option value="text">Text Box</option>
            <option value="checkbox">Check Box</option>
        </select>
        <button id="remove1">Remove</button>
        <br/><label>Answer #1 : </label>
        <div id="Answers1">
            Option 1: <input type="text" id='answerbox11' name='answerbox1'  value="" />
            <br/>Option 2: <input type="text" id='answerbox12' name='answerbox1'  value="" />
            <br/>Option 3: <input type="text" id='answerbox13' name='answerbox1'  value="" />
            <br/>Option 4: <input type="text" id='answerbox14' name='answerbox1'  value="" />
        </div>
    </div>
</div>

I tried to do something like onchange and then get the ID and go from there but that didn't work. I know it doesn't match the back end jquery name.

TL;DR

  1. I don't know how to dynamically write the jQuery function to work for all of them.
  2. I don't know why even if I hardcode it to #choice1 it will work when its first created but not if i remove and add it even though it has the same exact values. I think it might MAYBE have to do with for loop, because the alert doesn't even trigger the second time around.

You could try

$(document).on("change", ".selector", function(){
  //do something

});

//Edit

Add to the select element class for example select-option and a tag that will hold the select's counter

//JS    
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...

and then your on change function would look something like

$(document).on("change", ".select-option", function(){
  //do something
  var selected_type = $(this).attr('value');
  var ans_number = $(this).attr('number');
  $("#answerbox"+ans_number).children('input').attr('type', selected_type);
});

I hope this will help :)

对于动态添加的元素,请使用

$(selector).on("change", callback)

If element is dynamic then Jquery will not bind directly as

$('#choice1').change(function (){});

But for that you need to call same function with some static element. For Ex:

 $(".listingDiv").find('#choice1').change(function (){});

or

$(document).find('#choice1').change(function (){});

and it will work. try it.

When elements will be aded dynamically, best practice is to delegate the handler(s). Put your handler on the containing div or window/document .

  • First

     <select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems. 

    This is one reason your never be called. If you bind an event listener to an element, you should not write the actual JS code inside the element.

  • Second

    Bind your listener like this:

 $('#choice1').on("change", function () { var selected_item = $(this).val() var searchEles = document.getElementById("Answers1").children; alert(searchEles.length); for(var i = 0; i < searchEles.length; i++) { $('#answerbox1' + i).attr('type', selected_item); //alert(searchEles.length); } }); 

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