Copy value from input 1 to input 2 onclick - javascript

Looking for a script that copies input value 1 to input 2 on button click and add +1 to sets text box.
b = document.getElementById('tussenstand').value;
var theTotal1 = b;
$(document).on("click", "#button1", function(){
theTotal1 = Number(theTotal2)
$('#eindstand').val(theTotal2);
});
$('#eindstand').val(theTotal2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="tussenstand"></input>
<input id="eindstand"></input>
<input id="sets"></input>
<button id="button1">click</button>
Thanks in advance.

I think this will do it.
$(document).on("click", "#button1", function(){
var total = document.getElementById('tussenstand').value;
$('#eindstand').val(total);
var sets = parseInt($('#sets').val());
$('#sets').val( (sets || 0) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="tussenstand"></input>
<input id="eindstand"></input>
<input id="sets"></input>
<button id="button1" onclick="">click</button>

$('#button1').click(function(){
$('#eindstand').val($('#tussenstand').val());
$('#sets').val(Number($('#sets').val())+1);
});
check here : jsfiddle
Edited as you commented

The code below should work. There are several issues that will help you in the future. In the HTML the function that is triggered via the onclick will interfere with the jQuery onclick. You may want to remove it.
onclick="bereken();
The way that you have your code the b variable is not declared.
b=document.getElementById('tussenstand').value;
The way that the jQuery onclick is written should have a narrower scope (not the document). The way that it is now every time you click any were in the document it fires. I changed this:
$(document).on("click", "#button1", function(){
to this:
$("#button1").on("click", function() {
The full edited code is here.
var count = 0;
$("#button1").on("click", function(){
if ( typeof b === 'number') {
count++;
$("#eindstand").val(b);
$("#sets").val(count);
}
});

Look at the JQuery API Documentation for the .on() method. The function doesn't take the target as a parameter, but as the caller object! EDIT: well, it would actually still work the other way around, but that makes event delegation. Only do that if you know what you're doing. I prefer changing this:
$(document).on("click", "#button1", function(){ ... });
into this:
$("#button1").on("click", function() { ... });
Which in vanilla JS would be:
document.getElementById("button1").addEventListener("click", function() { ... });
Next, you shouldn't need to define variables outside of your function, and naming variables with numbers in them is a bad practice. Try to make the names as clear as possible.
Now that this is clear, here's how I'd write it:
$("#button1").on("click", function() {
$("#eindstand").val($("#tussenstand").val());
$("#sets").val(parseInt($("#sets").val())+1);
});

To achieve that use:
$(function() { //on DOM ready
$('#button1').click(function(){ //Attach event
//Get value safe - can use parseFloat() too:
val1 = parseInt($('#tussenstand').val());
val2 = parseInt($('#eindstand').val());
sets = parseInt($('#sets').val());
//Make sure we are using integers:
if (isNaN(val1) || isNaN(val2) || isNaN(sets)) return;
//Add
$('#eindstand').val(val1 + val2);
//Increment:
$('#sets').val(sets+1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="tussenstand" type='number' />
<input id="eindstand" value='0' type='number' />
<input id="sets" value='0' type='number' />
<button id="button1">click</button>

Related

Same AJAX call for multiple button on clicks on the same page [duplicate]

I have multiple buttons containing different values.
My buttons :-
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Now, if I click on Button1, I should get it's value. That is 1, and if I click Button2, I should get value 2.
I have written this code :-
<script type="text/javascript">
$("button").click(function() {
var fired_button = $("button").val();
alert(fired_button);
});
</script>
But it always alerts 1. What must I do to fix my code?
UPDATED
Use this instead of button in :
var fired_button = $("button").val();
You have to use this to target the current button clicked instead of button that will select all buttons in the DOM, .val() makes it to get the value of the first button.
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
You need to use this variable in order to access the clicked button's value.
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
This would return the value of the button.
You could try something as simple as:
$(this).val();
$(function(){
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Note: you should add your event listeners after the document is ready. This is why, I have enclosed the event handler in the
$(function{})
This is a shorthand of
$(document).ready(function(){})
For more information about this, please have a look here.
Use this inside the click handler
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Try with $(this).val();. It will return clicked button value.
If you're using jQuery, you're looking for the .attr() function.
$(this).attr("value")
That code will give you the value attribute of the html element designed by $(this) (or you precise the ID of the element).
Try $(this).val().
'this' always refers to the current object.
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Plain JavaScript solution with ES6 syntax:
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', () => {
const fired_button = button.value;
alert(fired_button);
});
});

Detect changes made to input through code

Somewhere in my page I have an button that when clicked changes the value of another input. However I don't have control over the code where the click event is defined (on a clients' CDN) and I didn't bother to look. I just want to capture the event when my inputs' value is change through the code. Here's an example:
HTML
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
JS
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#myinput").on("input change bind",function(e) {
$("#message").text("changed " + i++);
});
Here's a fiddle where you can test the situation: http://jsfiddle.net/fourat05/t9x6uhoh/
Thank you for your help !
There's an incredibly hacky way to do this.
What you do is replace the jQuery.fn.val function with your own implementation, and call the old implementation from the new one. This technique is a kind of Monkey patching.
The implementation is as follows:
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + ++i);
});
var handleChanges = function(){
$("#message").text("changed " + i);
}
var oldval = jQuery.fn.val;
jQuery.fn.val = function(){
oldval.apply(this,arguments);
if(this.attr('id') === 'myinput'){ //and possibly add a check for changes
handleChanges();
}
}
$("#myinput").on("input change bind",function(e) {
i++;
handleChanges();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
However, I strongly recommend against using it, because:
This alters the behaviour of a widespread library, thus creating possible pitfalls for the developers producing code for the same page
It will quickly become complicated to detect multiple events on multiple elements.
Please understand the side effects of this method before implementing it.
Values changed directly in the DOM dont trigger those events, but since you have an action that is called to change the value, you can trigger the input change event.
$("#theonechanging").on("click", function(e) {
$("#myinput").trigger("change");
});
fiddle
use triggers
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#theonechanging").on("click", function(e) {
$("#myinput").trigger("change");
});
$("#myinput").on("input change bind",function(e) {
$("#message").text($("#myinput").val());
});
Fiddle
I think it is not possible without changing the script for BUTTON.
When the user click the 'Button', you should trigger another function to catch the change in 'Input'.
If you don't want to change the 'Button' script, you can try something like the code below, seeking for the correct combination of events:
(check the list of events here: http://www.w3schools.com/tags/ref_eventattributes.asp)
<html>
<body>
<input type="text" id="myinput" onchange="change_Message('onchange')"
onclick="change_Message('onclick')"
oninput="change_Message('oninput')"
onkeypress="change_Message('onkeypress')"/>
<input type="button" id="theonechanging" value="Click Me" onclick="change_Input()"/>
<br />
<p id="message"></p>
<script>
var input_value = document.getElementById('myinput').value; // as global variable
function Test_if_Change()
{
if ( document.getElementById('myinput').value != input_value )
{
change_Message('Test_if_Change');
}
}
setInterval(Test_if_Changed, 10);
function change_Input() { document.getElementById('myinput').value = 'input changed by button'; }
function change_Message(event) { document.getElementById('message').innerHTML = 'message changed by '+event+' to: ' + document.getElementById('myinput').value; }
</script>
</body>
</html>
There is no perfect way to detect input value changes through code but if you you are using jquery ,you can hook the val function and trigger change event manually.
jQuery.fn._val = jQuery.fn.val;
jQuery.fn.val = function(){
jQuery.fn._val.apply(this,arguments);
if(arguments.lenght==1){
this.trigger('code-change');
}
}
}

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

How to refactor this simple code

I have a following script:
$(document).ready(function() {
$('#q1_6').on("click", function(event){
$('#q1-f').slideToggle(350);
});
$('#q1_7').on("click", function(event){
$('#q1-m').slideToggle(350);
});
$('#q1_15').on("click", function(event){
$('#q1-o').slideToggle(350);
});
$('#q2_6').on("click", function(event){
$('#q2-f').slideToggle(350);
});
$('#q2_7').on("click", function(event){
$('#q2-m').slideToggle(250);
});
$('#q2_15').on("click", function(event){
$('#q2-o').slideToggle(350);
});
$('#q3_13').on("click", function(event){
$('#q3-o').slideToggle(350);
});
});
Are these calls proper, or maybe I should somehow refactor the script to avoid duplication?
Edit:
I am creating a survey with about 20 questions displayed on one page. Answers are in checkboxes. Some answers have additional options (sub-answers), which should be shown when user clicks parental answer. Here is HTML markup for better understanding
<div>
<input type="checkbox" id="q1_5"/><label for="q1_5">Answer 5</label>
</div>
<div>
<input type="checkbox" id="q1_6"/><label for="q1_6">Answer 6</label>
</div>
<div id="q1-f">
<div>
<input type="checkbox" id="q1_6_1"/><label for="q1_6_1">Answer 6-1</label>
</div>
<div>
<input type="checkbox" id="q1_6_2"/><label for="q1_6_2">Answer 6-2</label>
</div>
<div>
<input type="checkbox" id="q1_6_3"/><label for="q1_6_3">Answer 6-3</label>
</div>
</div>
Current script works well, but I am wondering if I can avoid repeats of the same code snippets.
If you have access to the HTML and can influence the structure of the elements which when clicked initiate the toggle, then I'd add a class and data attribute:
<a href='#' id='q1_6' class='toggle' data-toggle-id='q1-f'>blah</a>
$(document).ready(function() {
$('a.toggle').on('click', function(){
var $el = $(this),
toggleID = '#' + $el.attr('data-toggle-id'),
toggleValue = 350;
$(toggleID).slideToggle(toggleValue);
});
});
given no idea on how IDs are correlated in your example.
function toggle(id, id2, value){
$(id).on("click", function(event){
$(id2).slideToggle(value);
});
}
toggle('#q1_15', '#q1-0', 350);
You could do :
$('[id^="q"]').on("click", function(e){
//get the id of the clicked button
var id = e.target.id;
switch(id){
//do all cases based on id
}
});
This could be done in an even cleaner way if there is some element to which we could delegate the event handling, but you didn't show us your markup. It would be something like
$('body').on("click",'[id^="q"]', function(e){
//get the id of the clicked button
var id = e.target.id;
switch(id){
//do all cases based on id
}
});
This second option use only one event handler (good) but it has to wait until the event is bubbled up the DOM (might be bad)
Why don't you create a javascript object where keys denote the id of element that accepts clicks and corresponding value is the id of element to show. Something like:
var clickHanders = {
"q1_6": "q1-f",
"q1_7": "q1-m"
// ...
};
Then all you need is:
$(document).ready(function() {
$("div[id^=q]").on("click", function(event) {
var srcId = this.id;
var dstId = clickHanders[srcId];
if (dstId) {
$("#" + dstId).slideToggle(350);
}
});
});
Edit
I now see that the slide duration can be different as well. You can still use the above approach:
var clickHanders = {
"q1_6": {
"elementId": "q1-f",
"duration": "350"
},
"q2_7": {
"elementId": "q2-m",
"duration": "250"
}
//...
};
$(document).ready(function() {
$("div[id^=q]").on("click", function(event) {
var srcId = this.id;
var dstData = clickHanders[srcId];
if (dstData) {
$("#" + dstData.elementId).slideToggle(dstData.duration);
}
});
});
This code looks longer than your original code but perhaps more sensible.
There are some things to ask when you refactor:
Are you having speed problems?
Are you having memory problems?
Does the code look ugly?
You should not be refactoring code just to refactor it and optimize something where it is not needed. If the code is not too slow and does not have a too high memory consumption (all in the eye of the beholder) and is readable, you have good code.
My idea would be to serialize the event trigger, event target and slideToggle amount, so you could iterate through some kind of Collection and bind it. But would that be worth it?
Well, each handler does the very same thing, so here's what you should do:
Refactor your HTML, for example:
<div id="q1-6" data-to="q1-f"></div>
for each object (you can use other HTML attributes). Then you can define handlers:
$('#q1-6,#q1-7,#someother_id,#watman,#foo').click(function() {
var id = $(this).attr('data-to');
$('#'+id).slideToggle(350);
});
There is no way to shorten your code, because there is nothing exactly the same, so your code is ok.

replacing element with jQuery

I have <form>s on my page that I want to replace with <button>s. The thing that is causing me difficulty is that I want to use the value of the <form>'s submit input as the html for the button.
<form action="/postcomment/" method="post">
<inputs>
.
.
.
<input type="submit" value="Reply">
</form>
Becomes
<button class="postcomment">Reply</button>
I'm having a hard time wrapping my mind around the chaining here. I need to grab the data values (e.g. "Reply") and then insert them into the button elements in one jQuery operation (or else manage the ordering with something like .index()) and I haven't figure out how to do that yet.
Working example here: http://jsfiddle.net/Mch86/
$(document).ready(function(){
$('form').each(function(){
button = $('<button>' + $('input[type="submit"]', this).val() + '</button>').addClass($(this).attr('action').replace(/\//g, ''));
$(this).replaceWith(button);
});
});
Do something like this:
$('input[type="submit"]').replaceWith(function () {
return $('<button>').text(this.value).addClass('postcomment');
});
jsFiddle Demo
This will replace all of your submit buttons (<input type="submit">) with a <button>, keeping the text on the button.
replaceWith() allows you to use a function as its parameter, which has a reference to the individual submits themselves (this).
Since you said you have multiple forms:
$(function() {
$('form').each(function() {
var str = $(this).find('input[type="submit"]').val();
$(this).replaceWith($('<button/>').addClass("postcomment").text(str));
});
});
You could do:
var label = $('form input:submit').val();
var action = $('form').attr('action').replace(/\//g, '');
var button = $('<button />', { class: action});
button.html(label);
$('form').replaceWith(button)
;
fiddle here: http://jsfiddle.net/be3af/1/

Categories

Resources