Add text to an input field x when user clicks button x - javascript

I have a list of text inputs, each with an associated button. Here's my setup: jsfiddle
I can get it working individually (see the top button which is working),
But how can I make it so clicking any of the buttons will change the text of its associated input (button# --> text#), without repeating the code for each item?
HTML:
<input type="text" id="text1" style="width: 150px;" /><input type="button" value="Click Me" id="button1" /><br/>
<input type="text" id="text2" style="width: 150px;" /><input type="button" value="Click Me" id="button2" /><br/>
<input type="text" id="text3" style="width: 150px;" /><input type="button" value="Click Me" id="button3" /><br/>
<input type="text" id="text4" style="width: 150px;" /><input type="button" value="Click Me" id="button4" /><br/>
<input type="text" id="text5" style="width: 150px;" /><input type="button" value="Click Me" id="button5" /><br/>
jQuery:
$(function () {
$('#button1').on('click', function () {
var text = $('#text1');
text.val('Stuff');
});
});

Bind event on all the buttons using the attribute selector. $('[id^=button]') will select all the elements whose id starts with button
Use $(this) inside the event handler to access the element that was clicked.
Use prev, will select the previous sibling of the element.
I recommend to add same class to all the buttons, so that event can be bound using the class. $('.myButtons').on('click', function() {});, and then you no longer need id on each of the button. This is also useful to style all the elements.
$('[id^=button]').on('click', function() {
$(this).prev().val('Stuff');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id="text1" style="width: 150px;" />
<input type="button" value="Click Me" id="button1" />
<br/>
<input type="text" id="text2" style="width: 150px;" />
<input type="button" value="Click Me" id="button2" />
<br/>
<input type="text" id="text3" style="width: 150px;" />
<input type="button" value="Click Me" id="button3" />
<br/>
<input type="text" id="text4" style="width: 150px;" />
<input type="button" value="Click Me" id="button4" />
<br/>
<input type="text" id="text5" style="width: 150px;" />
<input type="button" value="Click Me" id="button5" />
<br/>
The above code will not work if you change the HTML structure. You can use more flexible approach as below
Use data-* custom attributes to store the association of the button with the textbox.
When the button is clicked get the value of the data-target attribute and update the value of the corresponding textbox.
$('.button').on('click', function() {
$($(this).data('target')).val('Stuff');
});
.text {
width: 150px;
border: solid 1px green;
}
.button {
border: solid 1px green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id="text1" class="text" />
<input type="button" value="Click Me" class="button" data-target="#text1" />
<br/>
<input type="text" id="text2" class="text" />
<input type="button" value="Click Me" class="button" data-target="#text2" />
<br/>
<input type="text" id="text3" class="text" />
<input type="button" value="Click Me" class="button" data-target="#text3" />
<br/>
<input type="text" id="text4" class="text" />
<input type="button" value="Click Me" class="button" data-target="#text4" />
<br/>
<input type="text" id="text5" class="text" />
<input type="button" value="Click Me" class="button" data-target="#text5" />
<br/>

You can use and attribute start with selector and prev()
$(function() {
$('[id^=button]').on('click', function() {
var text = $(this).prev();
text.val('Stuff');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1" />
<input type="button" value="Click Me" id="button1" />
<br/>
<input type="text" id="text2" />
<input type="button" value="Click Me" id="button2" />
<br/>
<input type="text" id="text3" />
<input type="button" value="Click Me" id="button3" />
<br/>
<input type="text" id="text4" />
<input type="button" value="Click Me" id="button4" />
<br/>
<input type="text" id="text5" />
<input type="button" value="Click Me" id="button5" />
<br/>

$(function () {
$('input:button').on('click', function () {
var text = $(this).prev();
text.val('Stuff');
});
});
Use input:button as selector and use .prev()
demo

Here is a Jsfiddle:
enter link description here
The code:
$(function () {
$('.button').on('click', function () {
console.log(1)
var this_id = $(this)[0].id.split('button')[1];
console.log(this_id)
$('#text' + this_id).val('Stuff');
});
});

For buttons use class atribute. like
<input type="text" id="text1" style="width: 150px;" /><input type="button" value="Click Me" id="button1" clas="btn"/>
Then use .btn as selector . on clicking this get its previous sibling which is input type="text" . Instead of class you can use same name for all buttons also.
Javascript;
$(function () {
$('.btn').on('click', function () {
var text = $(this).prev();
text.val('Stuff');
});
});

If you prefer a vanilla Javascript version:
document.addEventListener('DOMContentLoaded', function() {
[].forEach.call(document.querySelectorAll('input[id^=button]'), function(el, i) {
el.addEventListener('click', function(e) {
this.previousElementSibling.value = 'Stuff';
});
});
});
Explaining the code:
When all the elements of the pages are already loaded / ready for use
We loop through all the input fields which id starts with button
For each of those elements, we add a click event handler
When the event is triggered, we look for the previousElementSibling of the button clicked
And then, we change its value to 'Stuff', as your example says.

Try selecting input type="text" having id where last character corresponds to clicked input type="button" element id last character
$("input[type=button]").click(function() {
$("input[type=text][id$=" + this.id.slice(-1) + "]").val(this.id /* "Stuff" */)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1" style="width: 150px;" />
<input type="button" value="Click Me" id="button1" />
<br/>
<input type="text" id="text2" style="width: 150px;" />
<input type="button" value="Click Me" id="button2" />
<br/>
<input type="text" id="text3" style="width: 150px;" />
<input type="button" value="Click Me" id="button3" />
<br/>
<input type="text" id="text4" style="width: 150px;" />
<input type="button" value="Click Me" id="button4" />
<br/>
<input type="text" id="text5" style="width: 150px;" />
<input type="button" value="Click Me" id="button5" />
<br/>

First you can select all buttons like this $( ":button" ) to avoid calling each button individually.
then you can get the textbox using .prev()
so your code should be like this
$(function () {
$( ":button" ).on("click",function(){
var $txt= $(this).prev();
$txt.val("Hello World");
});
});
You may test that at this fiddle

Related

Cookies aren't firing when button clicked

I'm trying to fire a cookie saving the persons first name when a button is clicked. And then show the cookie when the read cookie button is clicked.
However, the cookie doesn't seem to be saving?
<form id="myform">
<input type="text" id="fname" value="First name"><br />
<input type="text" id="lname" value="Last name">
</form>
<input id="btnAdd" type="button" value="Add Cookie" />
<input id="btnRead" type="button" value="Read Cookie" />
<script type="text/javascript">
$(function () {
$("#fname").click(function () {
$.cookie("Name", $("#fname").val());
});
$("#btnRead").click(function () {
alert($.cookie("Name"));
});
});
</script>
<form id="myform">
<input type="text" id="fname" value="First name"><br />
<input type="text" id="lname" value="Last name">
</form>
<input id="btnAdd" type="button" value="Add Cookie" />
<input id="btnRead" type="button" value="Read Cookie" />
<script type="text/javascript">
$(function () {
$("#btnAdd").click(function () {
$.cookie("Name", $("#fname").val());
});
$("#btnRead").click(function () {
alert($.cookie("Name"));
});
});
</script>

hiding/closing a div opened by .show()

When my page loads I hide a div containing a form using
$('#popupPerson').hide();
then in the body I build a table and this popup to help insert/update/delete row data using a form that is initally hidden
<div id="popupPerson" class="popupPerson">
<form id="form_popup_person" action="person_update" method="post">
<fieldset>
<legend>Person</legend>
<label for="id">id</label> <input name="id" type="number" />
<label for="revision">revision</label> <input name="revision" type="number" /><p>
<label for="lastName">lastName</label> <input name="lastName" type="text" />
<label for="firstName">firstName</label> <input name="firstName" type="text" /><p>
<label for="street">street</label> <input name="street" type="text" />
<label for="city">city</label> <input name="city" type="text" /><p>
<label for="county">county</label> <input name="county" type="text" />
<label for="state">state</label> <input name="state" type="text" />
<label for="postalCode">postalCode</label> <input name="postalCode" type="text" /><p>
<label for="birthDate">birthDate</label> <input name="birthDate" type="text" />
<label for="email">email</label> <input name="email" type="text" />
<label for="status">status</label> <input name="status" type="text" /><p>
<input name="submit" type="submit" value="Submit" />
<input name="cancel" type="submit" class="cancel" value="Cancel" />
<button type="button" class="cancel" onClick="this.parent.close();">Cancel button</button>
<button type="button" class="cancel" onClick="$(this).parent().parent().hide();">parent parent hide button</button>
<button type="button" class="cancel" onClick="$(this).parent().hide();">parent hide button</button> <!-- makes ALL BUTTONS DISAPPEAR -->
<button type="button" class="cancel" onClick="$(this).hide();">hide button</button> <!-- makes the BUTTON ITSELF DISAPPEAR -->
</fieldset>
</form>
</div>
and some js so that if a row in the table is clicked this fires and makes the div visible
$('#popupPerson').show();
I want to add a "Cancel" button to the form that simply closes/hides the div - no submitting, no resetting.
you can simply write like
<button type="button" class="cancel" onClick="$('#popupPerson').hide();">Cancel</button>
I would use this: <button type="button" class="cancel" onClick="$(this).closest('.popupPerson').hide();">parent parent hide button</button> which closes the containing .popupPerson, incase you ever need more than one on a page.
Alternatively, you can put this in a script:
$(function(){
$(document).on('click','.popupPerson .cancel', function(){
$(this).closest('.popupPerson').hide();
// Do whatever else you want here, like eat the event (stopPropegation, etc).
});
});
And this is the element:
<a class="cancel">parent parent hide button</a>

How to merge arrays from different input values.?

There are many text field with same name and same class with different values and each input have 1 button. I get the value from each one of the fields by clicking on each specific button. Using with Javascript. And i can put that value into array but the arrays are not merge. If i click on 1st button the specific input field value is put into the array, then i click on 3rd button the 1st value in array is removed and the new vlaue (3rd row's value) is stored in array. How can i store all of the values in same array on each click button.
Here is my code.
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="bbb"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="ccc"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="ddd"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="eee"/>
<input type="button" class="clickme" value="Get Value" />
</div>
Here is my javascript
<script type="text/javascript">
//Get the value on button click
var div = $(this).closest('div');
var get_eupdid = div.find('input').val();
alert(get_eupdid);
//Push the value into array.
var array_id = [];
array_id.push(get_eupdid);
console.log( "array_id: " + array_id);
</script>
Try this :Click function not there and declare the array as a global
var array_id = [];
$('.clickme').click(function(){
var get_eupdid= $(this).closest('div').find('input').val();
array_id.push(get_eupdid);
console.log( "array_id: " + array_id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="bbb"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="ccc"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="ddd"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="eee"/>
<input type="button" class="clickme" value="Get Value" />
</div>
I think you should check this out. There's usually no need for <input type='hidden' /> when you can use something else to store the data. Also, it shows you how, with a little bit of CSS, unless you'd like to put something else in those <div>s, how you can do that.
$(function(){
var possible = ['aaa', 'bbb', 'ccc', 'ddd', 'eee'], collection = [];
$('.clickme').each(function(i, e){
$(e).click(function(){
collection.push(possible[i]);
console.log(collection);
});
});
});
.clickme{
display:block;
}
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
</head>
<body>
<div>
<input type='button' class='clickme' value='Get Value' />
<input type='button' class='clickme' value='Get Value' />
<input type='button' class='clickme' value='Get Value' />
<input type='button' class='clickme' value='Get Value' />
<input type='button' class='clickme' value='Get Value' />
</div>
</body>
You need to make array global.Right now you are creating array every time a button is clicked so only current value remain in array
var array_id = [];
$(document).ready(function () {
$(".clickme").click(function () {
var div = $(this).closest('div');
var get_eupdid = div.find('input').val();
alert(get_eupdid);
//Push the value into array.
array_id.push(get_eupdid);
console.log("array_id: " + array_id);
});
});

How to get only one value from multiple input text field with same name?

I want to know how to get value from specific input text field. There are many text field with same name and same class with different values and each input have 1 button. How can i get the value from each one of the fields by clicking on each specific button. Using with Javascript or Jquery? Please guide me.
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="bbb"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="ccc"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="ddd"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="eee"/>
<input type="button" class="clickme" value="Get Value" />
$('.clickme').click(function() {
alert($(this).prev().val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa" />
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="bbb" />
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="ccc" />
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="ddd" />
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="eee" />
<input type="button" class="clickme" value="Get Value" />
On click of button use this context to get the button clicked.
Use .prev() to get the previous element which is the input.
Use .val() to get the value.
try to encapsulate the buttons and inputs with a div
from the button event get this (the button)
with $(this).closest('div') get to parent and get the next input from there.
$(document).ready(function() {
$('.clickme').click(function() {
var div = $(this).closest('div');
alert(div.find('input').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="bbb"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="ccc"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="ddd"/>
<input type="button" class="clickme" value="Get Value" />
</div>
<div>
<input type="hidden" name="myvalue" class="form-control input_text" value="eee"/>
<input type="button" class="clickme" value="Get Value" />
</div>
Try this
$(document).ready(function () {
$("input.clickme").click(function () {
alert($(this).prev('input[name=myvalue]').val());
});
});
this will be current clicked button and prev('input') will select above input element. see below code.
$(document).ready(function () {
$(".clickme").on('click',function(){
alert($(this).prev('input').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="bbb"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="ccc"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="ddd"/>
<input type="button" class="clickme" value="Get Value" />
<input type="hidden" name="myvalue" class="form-control input_text" value="eee"/>
<input type="button" class="clickme" value="Get Value" />

Get dynamic id when keyup triggering using jquery/javascript

I have dynamically showing product list with price and quantity in text box, i want to calculate product total price when enter the quantity.I have done this by onclick when increase or decrease button.but i also need to calculate the total price when key up quantity textbox
My code is like
<div id="gw_articles">
<div id="article_list">
<p>
<div id="article_1_element">
<input type="text" id="jform_article_1_name" name="jform[article_1][name] " value="Spark plug ARH-II AIW16 IRIDIUM+" disabled="disabled" size="35" /> <a id="jform_article_1_modal">Select an product</a>
<input type="hidden" id="jform_article_1_id" name="jform[article_1][id]" value="2" />
<input type="hidden" name="jform[article_1][price]" id="jform_article_1_price" value="30.00" class="inputbox" />
<input type="text" name="jform[article_1][price_total]" id="jform_article_1_price_total" value="90" class="inputbox" size="10" />
<input type="text" name="jform[article_1][quantity]" id="jform_article_1_quantity" value="3" class="inputbox" size="10" />
<input type="button" class="btn" value="+" onclick="document.id('jform_article_1_quantity').value++; calculateTotalPrice('jform_article_1')" />
<input type="button" class="btn" value="-" onclick="if(document.id('jform_article_1_quantity').value >1)document.id('jform_article_1_quantity').value--; calculateTotalPrice('jform_article_1')" />
<a title="test" class="btn btn-danger" onclick="removeElement('article_1_element')"> Delete </a>
</div>
</p>
<p>
<div id="article_2_element">
<input type="text" id="jform_article_2_name" name="jform[article_2][name] " value="Spark plug ARH-II AIW20 IRIDIUM+" disabled="disabled" size="35" /> <a id="jform_article_2_modal" class="btn modal" title="Select an product">Select an product</a>
<input type="hidden" id="jform_article_2_id" name="jform[article_2][id]" value="1" />
<input type="hidden" name="jform[article_2][price]" id="jform_article_2_price" value="40.00" class="inputbox" />
<input type="text" name="jform[article_2][price_total]" id="jform_article_2_price_total" value="40" class="inputbox" size="10" />
<input type="text" name="jform[article_2][quantity]" id="jform_article_2_quantity" value="1" class="inputbox" size="10" />
<input type="button" class="btn" value="+" onclick="document.id('jform_article_2_quantity').value++; calculateTotalPrice('jform_article_2')" />
<input type="button" class="btn" value="-" onclick="if(document.id('jform_article_2_quantity').value >1)document.id('jform_article_2_quantity').value--; calculateTotalPrice('jform_article_2')" />
<a title="test" class="btn btn-danger" onclick="removeElement('article_2_element')"> Delete </a>
</div>
</p>
</div>
<input type="hidden" id="articles_max" name="articles_max" value="2" />
</div>
So much going on in this code goodness. Try this:
function calculateTotalPrice(article) {
var price = and * multiplication - (some + addition);
$('#jform_article_2_total_price').val(price);
}
$('#jform_article_2_quantity').focusout(function(){
calculateTotalPrice('jform_article_2');
});
I sloved it by
`jQuery(document).ready(function($) {
jQuery("input[id*='quantity']" ).focusout(function(){
max_value = $("#articles_max").val();
var n =1;
jQuery("input[id*='quantity']" ).each(function(){
if (n <= max_value) {
id='jform_article_'+n;
calculateTotalPrice(id);
n++;
}
})
})
});
function calculateTotalPrice(field){
var price = document.id(field + "_price").value;
var quantity = document.id(field + "_quantity").value;
document.id(field + "_price_total").value = price * quantity;
}`

Categories