4

Dears i have below code that's make restrict to input with max value

it's working fine if the user tried to change it manually

but if the change happened dynamically from the jquery it's not working

$( "#materials" ).on('change','select',function(e){ var value = $(this).val(); if ((value !== '') && (value.indexOf('.') === -1)) { $(this).val(Math.max(Math.min(value, 3), 0)); // it's set the input value t 3 as max value } }); $( "#materials" ).val(300); // it's changing the value alawys 

so the last line change the input to 300, but if the user can't make it above 3

So how can i refuse any changing in the value even with dynamic changes

0

2 Answers 2

2

You should explicitly trigger change event while setting a value: $( "#materials" ).val(300).trigger('change');

Sign up to request clarification or add additional context in comments.

3 Comments

tried your code but no change and didn't trigger the event – Faisal just now edit
Hm. I did not use jQuery for a while. Maybe using .trigger('change') instead of .change() will help?
many thnx bro, the trigger ("'input") work like a charm :D, it's trigger the correct event
-1

I may be incorrect, but I don't believe that .val() triggers the 'change' event (which is reserved for user interaction).

What you might need to do is to move that validator function onto a setInterval(), like so:

setInterval(() => { let input = $("#materials"); let value = input.val(); if ((value !== '') && value.indexOf('.') === -1) { input.val(Math.max(Math.min(value, 3), 0)); } }, 0); 

What this does is cause the validation logic to run once per event loop for all elements with the id of "materials".

2 Comments

I would not recommend using of such approach as it will execute in every execution frame even if you don't need it to be executed.
We do not know whether or not OP has access to the portion of code responsible for dynamically changing the value of the materials field. The original question is asking for a method to validate dynamic changes, not how to make dynamic changes trigger a change event.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.