.change not triggered if change the value by js - javascript

In my web page the value of an input is changing by a js application, but what I want is to trigger an event when a value is changed.
The problem is that when the value is changed by the application, no event is triggered because the value is changed by js but if a value is input by the user the event is triggered.
Here is a small example of this, when you click on the change button, the value is changed but the .change event does not trigger.
If you manually input the values .change will trigger.
var i = 0;
$("#id_st").change(function(){
console.log('This is value',$(this).val())
$('#p').html($(this).val());
});
$('#change_btn').click(function(){
i = i+1;
$("#id_st").val(i);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_st" type="text" name="st" value="0">
<br>
<button id="change_btn" type="button" name="button">change value</button>
<br>
<p id="p">value</p>
I searched for my problem and found .trigger('change') but as I already told you that value is changed by an application which I haven't developed so can't use this method.
Please tell me a real solution for my problem.

On button#change_btn click , the change event of the input#id_st wont't be fired. This is because for input element to fire change event, first it's value must change and then it must loose focus. So when you click the button, it's value has changed but it never got focus to loose it later.
So you have to fire the 'change' event manually for which you can just chain trigger() once you set the value of the input with val() as
$("#id_st").val(i).trigger('change')
You can learn more here in MDN
Demo:
var i = 0;
$("#id_st").change(function(){
console.log('This is value',$(this).val())
$('#p').html($(this).val());
});
$('#change_btn').click(function(){
i = i+1;
$("#id_st").val(i).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_st" type="text" name="st" value="0">
<br>
<button id="change_btn" type="button" name="button">change value</button>
<br>
<p id="p">value</p>
EDIT:
Well if you can't use trigger(). You can check for change in value of the input periodically as suggested by #Mohammad.

use .on('input') and trigger('input')
var i = 0;
$("#id_st").on('input',function(){
console.log('This is value',$(this).val())
$('#p').html($(this).val());
// you may need to update i here to start from it after change
i = parseInt($(this).val());
});
$('#change_btn').click(function(){
i = i+1;
$("#id_st").val(i).trigger('input');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_st" type="text" name="st" value="0">
<br>
<button id="change_btn" type="button" name="button">change value</button>
<br>
<p id="p">value</p>
Sorry!! misunderstanding here.. Unfortunately What I know is: you cannot make the change event fire itself without relation between the event/action and the input .. OR you have to use setInterval() to catch any change of input value after each amount of time
This is how to trigger the event using setInterval() without need to trigger the event in the uncontrolled application
var i = 0;
$("#id_st").on('input',function(){
console.log('This is value',$(this).val())
$('#p').html($(this).val());
// you may need to update i here to start from it after change
i = parseInt($(this).val());
});
$('#change_btn').click(function(){
i = i+1;
$("#id_st").val(i);
});
// setInterval every 5 seconds
setInterval(function(){
$("#id_st").trigger('input');
} , 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_st" type="text" name="st" value="0">
<br>
<button id="change_btn" type="button" name="button">change value</button>
<br>
<p id="p">value</p>

After doing some research on MDN web docs, i found some stuff on manually firing events Dispatch Event Function Examples
var i = 0;
$("#id_st").change(function(){
console.log('This is value',$(this).val())
$('#p').html($(this).val());
});
$('#change_btn').click(function(){
var event = new Event('change');
var target = document.getElementById('id_st');
i = i+1;
$("#id_st").val(i);
target.dispatchEvent(event);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_st" type="text" name="st" value="0">
<br>
<button id="change_btn" type="button" name="button">change value</button>
<br>
<p id="p">value</p>

If you're not the one who's changing the value, then I think there's only one way to trigger the change, you'll have to put a setTimOout() function on the input which will take the value of the <p> and check if it's different from the one before.
(In page load capture the <p> value and every time your setTimeOut() runs update that value).
If it's different then trigger the change with jQuery.

Related

Cant Get Answer Back In answer Box NAN is being shown

it does not returns prpoer answer it returnes NAN in Answer
<html>
<head>
<script type="text/javascript">
function pro(n,p)
{
var number=parseInt(n);
var powe=parseInt(p);
for(var i=1;i<powe;i++)
{
number*=number;
}
document.getElementById("answer").value=number;
}
</script>
</head>
<body>
<form name="F" >
Enter Number <input type="text" name="num" id="num"/>
Enter Power <select name="powe" id="powe">
<option value="2" >square</option>
<option value="3" >cube</option>
</select>
Answer<input type="text" name="Answer" id="answer" />
<input type="button" onClick="pro(num,powe)" value="Calculate" />
</form>
</body>
</html>
The issue is this: onClick="pro(num,powe)". Instead of the values for num and powe being gotten from the input elements and passed into the pro function, the actual element references (which are not numbers) are being passed.
To solve this problem, you'll need to get the values of the elements. But, before you just make a quick edit to your code, don't use inline HTML event attributes (onclick) in the first place. Instead, separate your JavaScript from your HTML and set up event handlers using modern standards with .addEventListener() as shown below.
Also (FYI):
Since you aren't actually submitting form data anywhere, you don't
need a <form> element.
It's not necessary to use parseInt with p.value because that
value is coming from your select and you've already set those at
whole numbers.
Don't bother with self-terminating tags (<input />) as you
gain nothing from using them.
If you are expecting only numeric input, it's better to use input
type=number which restricts the user input to numbers. Making this change also saves you from worrying about parseInt on the input number being misinterpreted as other bases than 10.
Since you don't want the user to be able to change the result of the
operation, it's better to display it in a non-editable element, like
a span.
It's a good idea to move your <script> element to just before the
closing body tag because, by the time the parser reaches that
point, all your HTML elements will have been parsed into memory.
<html>
<head>
</head>
<body>
<div>
Enter Number <input type="number" name="num" id="num">
</div>
<div>
Enter Power
<select name="powe" id="powe">
<option value="2">square</option>
<option value="3">cube</option>
</select>
</div>
<div>
Answer <span id="answer"></span>
</div>
<div>
<input type="button" value="Calculate">
</div>
<script>
// Get references to the inputs, the answer container and the button
let inputNum = document.getElementById("num");
let power = document.getElementById("powe");
let answer = document.getElementById("answer");
let btn = document.querySelector("input[type='button']");
// Set up the click event handler for the button
btn.addEventListener("click", function(){
// Now you need to get the input values and pass them
// to the function that will act with them
pro(inputNum.value, power.value);
});
function pro(n,p) {
var number = parseInt(n);
for(var i = 1; i < p; i++) {
number *= number;
}
answer.textContent = number;
}
</script>
</body>
</html>
Try
document.getElementById("answer").innerHTML = number

How to change a global variable inside jQuery selectors?

I'm developing a website, which is using jQuery.Inside this code I need to change the value of a variable inside a Jquery selector and get the changed value after it.Is it possible to do that?How can I achieve this?If possible, could show me a snippet/example code?
I've tried declaring the variable global, but without success too.
var index;
$(document).ready( function(){
$("#myButton1").click(function(){ //selector number 1
index = 1;
});
$("#myButton2").click(function(){//selector number 2
index = 2;
});
//after, i need the value of the index for another selector
//look this next selector is fired at the same time as the previous one!
$("button[id^=myButton"+index+"]").click( function(){ //selector number 3
...
}
}
How can I make the selector number 1 or 2 fire after the selector number 3?Is it possible?
Javascript executes code asynchronously. In other words, whole code executes at the "same time." So first, it will execute var index;. Since the jQuery .click is waiting for you to click the button, it will skip both of the .click functions and move on to the alert. Since index is undefined, it will say index=undefined. To fix that, move the alert's inside the .click function so that the alert will execute after you click the button.
var index;
$("#button1").click(function() {
index = 1;
alert("index = " + index);
});
$("#button2").click(function() {
index = 2;
alert("index = " + index);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1"></button>
<button id="button2"></button>
Or you could do it this way:
var index = 0;
$("#button1").click(function() {
index = 1;
});
$("#button2").click(function() {
index = 2;
});
setTimeout(function() {
alert("index = " + index);
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1"></button>
<button id="button2"></button>
The above method basically executes the alert after 5 seconds, so you can change the value of index as many times as you want in those 5 seconds. The default value is 0, but if you click the first button within those 5 seconds, the value of index changes to 1. Same for the second button.
The things that happen when you click one of the buttons are those you define inside the click-handler function (see here):
$("#button1").click(function(){
window.index = 1; // only this line!!!
});
Your call to alert() resides inside the ready-funtion and is therefore only called when the page is loaded. You need to put the alert inside the click handlers to call it "on click". Doing so, all three versions should work. Should look like this:
$("#button1").click(function(){
index = 1;
alert(index);
});
After your edit:
Same thing here: the selector string after you comment is created at the time of the page load, before any button is clicked. and never again after that.
At that moment, it evaluates to "button[id^=myButtonundefined]" because index has no defined value yet. T## is function therfore will be executed whenever you click a button whose ID starts with myButtonundefined - probably never.
Everything you want to achieve, for which you need the value of index you need to execute inside the click-handler function. e.g.:
$(document).ready( function(){
$("#button1").click(function(){
$("button[id^=myButton1]").click( function(){
...
});
});
$("#button2").click(function(){
$("button[id^=myButton2]").click( function(){
...
});
});
}
or you could try the following approach, which installs a click-handler on all myButton...'s and therein checks if the corresponding button... has been clicked before:
var index;
$(document).ready( function(){
$("#button1").click(function(){
index = 1;
});
$("#button2").click(function(){
index = 2;
});
//after, i need the value of the index for another selector:
$("button[id^=myButton]").click( function(){
if (this.id == 'myButton'+index) {
...
}
}
}
How to change a global variable inside jQuery selectors?
Don't use a global variable in this instance. You have a chance of a variable collision with any other code (jQuery or any other script you use). You can simply place index inside your document ready and use it in your example code and it will work without any chance of collision.
$(document).ready( function(){
var index;
$("#button1").click(function(){
index = 1;
});
$("#button2").click(function(){
index = 2;
});
//after, i need the value of the index for another selector:
$("button[id^=myButton"+index+"]").click( function(){
});
$('.js-getcurrentvalue').on('click', function() {
$('#currentvalue').val(index);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-getcurrentvalue" value="Get Current Value of Index"/><input type="text" id="currentvalue" /><br/>
<input type="button" id="button1" value="button1" /><br/>
<input type="button" id="button2" value="button1" /><br/>
But at the same time, the selector $("button[id^=myButton"+index+"]").click( function(){ }); fires.So, both are executed at the same time.I need that the second selector execute always after the first selector.Do u know how can I accomplish this?
This is not the original question you asked. Please read what an XY Problem is so your future questions can be answer correctly.
Highly recommended reading: Decouple your HTML, CSS and Javascript.
First we need to understand that each of these statements that attach an event handler onto an element all run before the event handler can be executed. So in my previous example the following events are registered:
$("#button1").click()
$("#button2").click()
$("button[id^=myButton]").click();
$('.js-getcurrentvalue').on('click')
You'll notice that I've done what any compiler would do and reduce the variable into it's actual value. At the time the event handler is attached, index has no value. Since this isn't what you want, you could write it like:
$("button").click(function() {
var $this = $(this);
var id = $this.prop(id);
if ($this.is("[id^=myButton"+index+"]") {
// do something as index changes
}
});
But it's really ugly and introduces an abstraction of a value to used to compare. It's also very tightly coupled, that is we have to place an event on any object we want to change index and we have to write more code for each button. Yikes. Instead we can use classes and the data-attribute with data() to simplify and make this more robust.
$(document).ready( function(){
var selector;
$(".js-enable-button").on('click', function(){
selector = $(this).data('selector');
});
$('.js-enable-me').on('click', function() {
var $this = $(this);
if ($this.is(selector)) {
alert($this.val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button1" />
<input type="button" class="js-enable-me" id="button1" value="Am I working?" /><br/>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button2" />
<input type="button" class="js-enable-me" id="button2" value="Or am I working?" /><br/>
Now the code is not limited to an Id. It's also not limited to a single selector. You could go crazy and just by adding only html the following continues to work for all elements. Notice I've added no additional code.
$(document).ready( function(){
var selector;
$(".js-enable-button").on('click', function(){
selector = $(this).data('selector');
});
$('.js-enable-me').on('click', function() {
var $this = $(this);
if ($this.is(selector)) {
alert($this.val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button1" />
<input type="button" class="js-enable-me" id="button1" value="Am I working?" /><br/>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button2" />
<input type="button" class="js-enable-me" id="button2" value="Or am I working?" /><br/>
<br/>
<input type="button" class="js-enable-button" value="I enable the three below me using id" data-selector="#id1,#id2,#id3" /></br>
<input type="button" class="js-enable-me" id="id1" value="id1" /><br/>
<input type="button" class="js-enable-me" id="id2" value="id2" /><br/>
<input type="button" class="js-enable-me" id="id3" value="id3" /><br/>
<br/>
<input type="button" class="js-enable-button" value="I enable the three below me using a class" data-selector=".enable" /></br>
<input type="button" class="js-enable-me enable" value="I'm .enable 1" /><br/>
<input type="button" class="js-enable-me enable" value="I'm .enable 2" /><br/>
<input type="button" class="js-enable-me enable" value="I'm .enable 3" /><br/>

Input text value into a div?

Say I have this text box:
<input type="text" id="myText" placeholder="Enter Name Here">
Upon pressing a button, I would like to send the value entered into this div:
<div id="text2"></div>
I'm not entirely sure how to do this. Do I create a function and call it to the div? How would I do that?
Could someone clear this up for me? Thanks.
Add an onclick to your button:
<input type="button" id="somebutton" onclick="addText()">
Then write the javascript:
function addText()
{
document.getElementById('text2').innerHTML = document.getElementById('myText').value;
}
Solution using onclick event:
<input type="text" id="myText" placeholder="Enter Name Here">
<div id="text2"></div>
<button id="copyName" onclick="document.querySelector('#text2').innerHTML = document.querySelector('#myText').value" value="Copy Name"></button>
JSFiddle: http://jsfiddle.net/3kjqfh6x/1/
You can manipulate the content inside the div from javascript code. Your button should trigger a function (using the onclick event), which would access the specific div within the DOM (using the getElementById function) and change its contents.
Basically, you'd want to do the following:
<!DOCTYPE html>
<html>
<script>
function changeContent() {
document.getElementById("myDiv").innerHTML = "Hi there!";
}
</script>
<body>
<div id="myDiv"></div>
<button type="button" onclick="changeContent()">click me</button>
</body>
</html>
Mark D,
You need to include javascript to handle the button click, and in the function that the button calls, you should send the value into the div. You can call $("#myText").val() to get the text of the text box, and $("#txtDiv").text(txtToAppend) to append it to the div. Please look at the following code snippet for an example.
function submitTxt() {
$("#txtDiv").text($("#myText").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myText" placeholder="Enter Name Here">
<button onclick = "submitTxt()"> Submit </button>
<div id="txtDiv"> </div>
HTML could be:
<input type='text' id='myText' placeholder='Enter Name Here' />
<input type='button' id='btn' value='click here' />
<div id='text2'></div>
JavaScript should be external:
//<![CDATA[
var pre = onload; // previous onload? - window can only have one onload property using this style of Event delegation
onload = function(){
if(pre)pre();
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
var text2 = E('text2'); // example of Element stored in variable
E('btn').onclick = function(){
text2.innerHTML = E('myText').value;
}
}
//]]>
I would recommend using a library like jQuery to do this. It would simplify the event handling and dom manipulation. None the less, I will include vanilla JS and jQuery examples.
Assuming the HTML in the body looks like this:
<form>
<input id="myText" type="text" placeholder="Enter Name Here">
<br>
<input type="submit" id="myButton">
</form>
<div id="text2"></div>
The Vanilla JS example:
//Get reference to button
var myButton = document.getElementById('myButton');
//listen for click event and handle click with callback
myButton.addEventListener('click', function(e){
e.preventDefault(); //stop page request
//grab div and input reference
var myText = document.getElementById("myText");
var myDiv = document.getElementById("text2");
//set div with input text
myDiv.innerHTML = myText.value;
});
When possible avoid using inline onclick property, this can make your code more manageable in the long run.
This is the jQuery Version:
//Handles button click
$('#myButton').click(function(e){
e.preventDefault(); //stop page request
var myText = $('#myText').val(); //gets input value
$('#text2').html(myText); //sets div to input value
});
The jQuery example assumes that you have/are adding the library in a script tag.

Javascript - disable buttons on value matched in input box

i am looking for solution i want to disable button if value of input box matched.
i got two buttons and an input box
<button type="button" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value="0"/>
i want to disable buttonpassvalue if input box (count) is zero and disable second button buttonpassvalue1 if value of (count) is 5
thanks for your help.
Made a JSFiddle for you!
http://jsfiddle.net/fRHm9/
Basically, you make a change event listener and, when it changes, grab the element whose id is equal to the input's value. I assigned the buttons ids of -1 and 1. Check out the fiddle.
Basically, you could achieve this quite easily using plain javascript. But, when using javascript in order to be able to find a specific element efficiently you will need to specify an id for that element. So I would recommend you to change your buttons so that they use id attributes as follows...
<button type="button" id="buttonpassvalue" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" id="buttonpassvalue1" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value=""/>
Note, that I added id attributes to each buttons. Now, you can run attach this javascript function to the keyup event of the text input element...
var input = document.getElementById('count');
input.onkeyup = function(){
var buttonpassvalue = document.getElementById('buttonpassvalue');
var buttonpassvalue1 = document.getElementById('buttonpassvalue1');
var val = this.value.trim();
if(val == "0"){
buttonpassvalue.setAttribute("disabled","disabled");
buttonpassvalue1.removeAttribute("disabled");
}
else if(val == "5"){
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.setAttribute("disabled","disabled");
}
else{
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.removeAttribute("disabled");
}
};
I have created a JS Fiddler where you can see a quick demo. Also, note that this solution is using plain javascript.

Javascript - set value attribute of progress element on javascript click event

I have a form tag with a progress tag and three submit as following:
<form>
<progress min="0" max="100" value="0"></progress>
<input type="submit" value="submit1">
<input type="submit" value="submit2">
<input type="submit" value="submit3">
</form>
I have a little js code which listens click event and changes the value of progress bar.
;(function(){
document.body.addEventListener('click', function(){
var p = document.querySelector('progress');
var s = document.querySelector('input');
var val;
if(s.value=="submit1"){
val=33;
}
if(s.value=="submit2"){
val=66;
}
if(s.value=="submit3"){
val=100;
}
p.value=val;
}, false);
}());
But the progress bar is not working as expected.
Any point where I can solve this?
About document.querySelector:
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
So, the code always will return "submit1", because it is the first element in the document.
Also form's submit make callback to the page, and you can't see the changes, because the code will return to initial stage.
If you doesn't want to do the callback, just change inputs types to "button".
Also, I offer you to attach onclick event to each button and call functionality that you want.
EDIT: The worked code bellow.
<form>
<progress min="0" max="100" value="0" id="progressBar1"></progress>
<input type="button" value="submit1" onclick="SubmitProgress(33);" />
<input type="button" value="submit2" onclick="SubmitProgress(66);" />
<input type="button" value="submit3" onclick="SubmitProgress(100);" />
</form>
<script type='text/javascript'>
function SubmitProgress(valueToSet) {
document.getElementById("progressBar1").value = valueToSet;
}
</script>
In your javascript - a typo might is what killed the script. Instead of using
;(function(){
Use this:
$(function(){

Categories