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(){
Related
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.
I'm an absolute beginner and tried to find similar questions but couldn't. Apologies if this has been answered previously.
In my assignment we need to create a form with 2 text fields and 1 button. The fields are for height and width and the idea is that onclick on the button will send the 2 parameters to a function that will change the height + width attributes for a photo. I know I'm doing something wrong because the picture simply disappears. Ideas? Thanks!
<html>
<head>
<script>
function borderResize(height1, width1)
{
document.getElementById('Amos').height = height1;
document.getElementById('Amos').width = width1;
}
</script>
</head>
<body>
<img src="Amos.jpg" id="Amos" />
<form>
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" value="click!" onclick="borderResize('height.value', 'width.value')"/>
</form>
</body>
</html>
When you write
onclick="borderResize('height.value', 'width.value')"
in means that on click borderResize function will be invoked with two string arguments, literally strings "height.value" and "width.value". In your case you want something like this
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
In above case you are selecting element from DOM using getElementById method and then read its value property.
You should learn to use addEventListener(), I would recommend you not to use ugly inline click handler.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Here is an example with your code.
window.onload = function() {
document.getElementById('button').addEventListener('click', borderResize, true);
}
function borderResize() {
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
<img src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/s200x200/11034289_10152822971918167_2916173497205137007_n.jpg?oh=71de7a46a75a946cf1d76e5ab10c1cdc&oe=55889977&__gda__=1434173455_6127f174627ed6014c84e562f47bc44c" id="Amos" />
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" id="button" value="click!" />
However as for your immediate problem you can use
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
onclick="borderResize('height.value', 'width.value')"
here you pass to borderResize strings: 'height.value', 'width.value'.
You may get value of input from function:
function borderResize(height1, width1)
{
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
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.
I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.
On my original post I wasn't for sure on the amount of depth I should go to. Here is what I have been working on since the jQuery answer was posted:
I am attempting to execute a task which requires the user to choose and click one html button out of a series of buttons and then be required to choose another html button out of a series of buttons.
Essentially I would like the value of the first button selection to be passed as a parameter to a function that will run when the user clicks the second button. I'm just learning javascript and I'm lost.
Thank you
HTML:
<form id="scoreboard">
<div>
<input type="text" name="homeTeam" value="00" size="2" "readonly" id="homeTeamScore"/>
<input type="button" value="+1" name="add1" id="homeAdd1" class="homeScore" onClick="calcScore(1)"/>
<input type="button" value="-1" name="neg1" id="homeNeg1" class="homeScore" onClick="calcScore(4)"/>
</div>
<div>
<input type="button" name="homeP1" id="homeP1" class="player" value="24" style="text-align:center;"/>
<input type="text" name="homeP1Score" value="0" size="2" style="text-align:center;"/>
</div>
<div>
<input type="button" name="homeP2" id="homeP2" class="player" value="44" style="text-align:center;"/>
<input type="text" name="homeP2Score" value="0" size="2" style="text-align:center;"/>
</div>
</form>
Javascript:
function calcScore(amount) {
if(amount==1) {scoreboard.homeP1Score.value++;scoreboard.homeTeam.value++;}
else if(amount==4) {scoreboard.homeP1Score.value--;scoreboard.homeTeam.value--;}
}
$('.player').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('.homeScore').click(function() {
function addHomeScore(data)
});
});
Using jQuery:
$('#buttonId').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('#button2Id').click(function() {
yourFunction(data);
});
});
This method is better because it uses JavaScript scoping to avoid globals. Since JavaScript (especially with jQuery) sometimes has multiple threads/functions executing at the same time, it's very easy to run into problems with globals. They're also very hard to test and unsafe.
In raw JavaScript:
HTML:
<button class="button1" onclick="saveValue()" />
<button class="button2" onclick="callMethod()" />
JavaScript:
myGlobalVariable = null;
function saveValue(){
myGlobalVariable = "Value That Was Selected";
}
function callMethod(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
}
In jQuery:
HTML:
<button class="button1" />
<button class="button2" />
JavaScript:
myGlobalVariable = null;
$('button.button1').click(function(){
myGlobalVariable = "Value That Was Selected";
});
$('button.button2').click(function(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
});
setup some global variable in js. then on each button setup some onClick events that go and change the global var. then the next button click can check to see the value in the global var
<button onclick="myFunction()">Click me</button>