Home > other >  JavaScript onchange value, changes on every input
JavaScript onchange value, changes on every input

Time:06-07

Im trying to work with Bootstrap Modal Form. What I want to achive is when user open modal with dynamicaly generated form with filled inputs, and when user wants to change some values then email is going to be sent with new values.

Im using:

        let emlTitle = $('#queryEmailTitle');        
        $(document).on('change', emlTitle, function(titleVal) {
            
            var emlProofTitle = titleVal.target.value;
       
            $('#queryEmailTitle').val(emlProofTitle);

        });

        let emlBody = $('#queryEmailBody');
        $(document).on('change', emlBody, function(bodyVal) {
            
            var emlProofBody = bodyVal.target.value;

            $('#queryEmailBody').val(emlProofBody);

        });

But the problem is that when i change value of one input, for example #queryEmailTitle, then #queryEmailBody gets same value as new value #queryEmailTitle

Cane any one show me what Im doing wrong?

Thanks in adcance.

CodePudding user response:

From jquery's on():

.on( events [, selector ] [, data ], handler )

selector
Type: String
A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

The second argument to .on needs to be a string; you're passing a jquery object.

Giving:

$(document).on('change', "#queryEmailTitle", function(titleVal) {

Note that IDs must be unique, so if you have an queryEmailTitle on your page and another one on the dialog, you're likely to have issues.

CodePudding user response:

As per the jQuery documentation you are passing wrong parameters to .on function.

    let emlBody = $('#queryEmailBody');
    $(document).on('change', emlBody, function(bodyVal) {
        
        var emlProofBody = bodyVal.target.value;

        $('#queryEmailBody').val(emlProofBody);

    });

Refer https://api.jquery.com/on/

Rather than having 2 .on event listeners you could it with one function.

    $(document).on('change', function(event) {
        
        var val= event.target.value;

        if (event.target.id === 'queryEmailTitle') {
            $('#queryEmailTitle').val(val);
        }
        else if (event.target.id === 'queryEmailBody') {
           $('#queryEmailBody').val(val);
        }
    });
  • Related