Duplicate value of input for multiple inputs - javascript

i need put value of general price
for all inputs but only take the value for 1st input.
Code :
<script type="text/javascript">
$('#GPrecio').change(function () {
$('#Precio').val($(this).val());
});
</script>
HTML :
<input type='text' size='3' name='GPrecio' id='GPrecio'>
$table.="<td>Precio : <br><input type='text' size='3' name='Precio[]' id='Precio'></td>";
Thank for answers and the time.

This will take the value of #GPrecio and apply it to all input name=Precio[] elements
$('#GPrecio').blur(function () {
$('[name="Precio[]"]').val($(this).val());
});
Also, if you have more than one element with id="Precio", that is a problem. Better to not use IDs unless you need them. Is there a reason you're using the same ID for each? You would be better off using a data-attribute, like <input type='text' size='3' name='Precio[]' data-inputtype='Precio'>, in which case your function could be refined to:
$('#GPrecio').blur(function () {
$('[data-inputtype="Precio"]').val($(this).val());
});

Suggest you to use classes instead of ids if you are going to use the same value.
Your input row could be like this:
<input type='text' size='3' name='Precio[]' class='Precio'>
Assuming Precio is the class name for all your inputs in the table row.
$('#GPrecio').change(function () {
let newValue = $(this).val();
$(".Precio").each(function() {
$(this).val(newValue);
})
});

As you can't use multiple same id, change it to class first:
<input type='text' size='3' name='Precio[]' class='Precio'>
And then jQuery trigger:
<script type="text/javascript">
$('#GPrecio').change(function () {
var gpval = $(this).val();
$('.Precio').each(function( index ) {
$(this).val(gpval);
});
});
</script>

Related

Jquery one button updates multiple input fields on form

I am trying to update two input fields in a form when clicking one button. I actually had all the code right when using document.getElementById, but the form that I'm using strips the ID's I set away, so I can't use getbyid. If I know the form field name, how could I change my function to do the same thing? Please note that my form has more than two fields, including a submit button, so I don't want to update those.
This is what I used before (with the ID selector)
Html:
<input type="text" name="field-1" id="info1">
<input type="text" name="field" id="info2">
Populate
JS:
function addTxt(val, id,no)
{
var id = id;
for(var i=1;i<=no;i++){
document.getElementById(id+i).value = val[i-1];
}
}
Fiddle:
http://jsfiddle.net/qwz47phx/3/
Edited with a much simpler and readable approach
function addVal(obj) {
event.preventDefault(); // Prevent page scrolltop on anchor click
$.each(obj, function(k, v) {
$("input[name='"+ k +"']").val( v );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo">
<input type="text" name="bar">
<a href="#" onclick='addVal({foo:"Hello", "bar-baz":"World"})'>Populate</a>
Or with native JS (ES5+):
function addVal(obj) {
Object.keys(obj).forEach(function(name) {
document.querySelector('input[name="' + name + '"]').value = obj[name];
});
}
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="name-with-dashes">
<a href="#" onclick='addVal({foo:"Hello", bar:"World", "name-with-dashes": "Works !"})'>Populate</a>
If you have problems with IDs you can use querySelector to select inputs by name like this:
JS:
function addTxt(val, id, no) {
for (var i = 1; i <= no; i++) {
document.querySelector('input[name="' + id + i + '"]').value = val[i - 1];
}
}
HTML:
<input type="text" name="info1" id="info1">
<input type="text" name="info2" id="info2">
Populate
Demo: http://jsfiddle.net/iRbouh/qwz47phx/6/
I hope this will help you.
You can use a jQuery attribute= selector to grab by name instead of ID.
function addTxt(val, id,no)
{
for(var i=1;i<=no;i++){
var name = id+i;
$("input[name='"+name+"']").val(val[i-1]);
}
}
Please note that this function will be looking for names of info1, info2, info3, etc, just as your original script did. However, in the HTML, you have names of info and info-1. Either the names will have to be changed to fit the function, or the function can be slightly more intricate.
Fiddle: http://jsfiddle.net/qwz47phx/8/

Get attribute value from input text

I want to get attribute value of each input field.
<input type="text" id="qty" data-id="{{$item->rowid}}" value="{{$item->qty}}">
function goUpdateCart(){
$('input[type=text]').each(function(){
alert($('input[type=text]').getAttribute("data-id"));
})
}
My function can't work correctly
Well, .getAttribute("data-id"); isn't jquery method.
You can use any of the following to get the data-* attr:
$(this).data('id');
$(this).attr('data-id');
$(this).prop('dataset').id;
this.dataset.id;
So it could be any of the above one:
function goUpdateCart(){
$('input[type=text]').each(function(){
alert(this.dataset.id);
})
}
You need to use each iteration element contextthis in each function to target current element along with .attr('data-id') or .data('id'):
$('input[type=text]').each(function(){
alert($(this).data("id"));
});
Try this:
$('input[type=text]').each(function(){
alert($(this).attr("data-id"));
});
<input type="text" id="qty" data-id="{{$item->rowid}}" value="{{$item->qty}}">
function goUpdateCart()
{
var attribute=$('#qty').attr('data-id');
alert(attribute);
}

get multiple values from an input tag with js

im trying to write a code that will generate me several "input" tags to a html
page.
i want to make something like this:
<div id="here">
<input type='text' placeholder='book'>
<input type='text' placeholder='author'>
</div>
<button id="another-book">+</button>
each time that the button is clicked i want to add another input to the page
right after the previous input.
i do it in a js file with the code:
$('#another-book').click(function (e) {
$('#here').append($("<input type='text' placeholder='book'>");
$('#here').append($("<input type='text' placeholder='author'>");
});
my problem is that after the user created his inputs and filled them,
i want to get the values of them - for each pair of book and author,
i.e. i want to get in the end a list of pairs (book, author)
how can i do that?
Try something like this
$('#another-book').click(function(e) {
console.log($('#here').find('input').map(function() {
return this.value
}).get());
$('#here').append($("<input type='text' placeholder='book'>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="here">
<input type='text' placeholder='book'>
</div>
<button id="another-book">+</button>
There is extra $( without closing bracket.
this works for me
$('#another-book').click(function (e){
$('#here').append($("<input type='text' placeholder='book'>"));
});
EDIT:
to get book and author pair use this code from jsfiddle
To get first pair take first element from authors array and first from books.
Hope it helped
$('#another-book').click(function (e) {
var a = $('<input>', { text:"", type:"text", placeholder:"book" });
var b = $('<input>', { text:"", type:"text", placeholder:"author" });
var c = $('<span>',{}).append(a).append(b);
$('#here').append(c);
});
$('#g-val').click(function(){
var all = [];
$('#here > span').each(function(){
var $book = [
$(this).find('input[placeholder=book]').val() ,
$(this).find('input[placeholder=author]').val()
]
all.push($book);
});
console.log(all)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="here">
<span>
<input type='text' placeholder='book'>
<input type='text' placeholder='author'>
</span>
</div>
<button id="another-book">+</button>
<h4 id="s-value"></h4>
<button id="g-val">get all input[type=text] ...</button>
For values of all inputs in an array
$.map($("#here").find("input"),function(o,i){return $(o).val();});
EDIT
For list of pairs
$.map( $("#here").find("input[placeholder='book']"),
function(o,i){
var book = $(o).val();
var author = $(o).next("input[placeholder='author']").val();
if (book == "" || author == "")
{
$(o).remove();
$(o).next("input[placeholder='author']").remove();
}
else
{
return { "book": book,
"author": author };
}
}
);

I'm trying to assign a variable to check-boxes and adding that variable to an output variable when it's checked

I'm very new to Javascript and would appreciate ANY help! I'm also using a jQuery library if that changes anything.
What I need is that if the first checkbox was ticked the output should be 100kcal, while if both were ticked then it should add up to 300kcal. My problem is that when I untick it adds the variables AGAIN.
HTML:
<input type=checkbox onchange="myFunction(100)" value="scrambledEggs">Scrambled Eggs</input>
<input type=checkbox onchange="myFunction(200)" value="bacon">Bacon</input>
<p id="output">0kcal</p>
JS:
var result = 0;
function myFunction(x) {
if (this.checked) {
result -= x;
document.getElementById("output").innerHTML = result + "kcal";
}
else {
result += x;
document.getElementById("output").innerHTML = result + "kcal";
}
}
Firstly if you're using jQuery, you should use it to attach the event handlers instead of onchange attributes. Secondly, the input tag is self closing - your current HTML is invalid. Finally, you can use a data attribute to store the kcal value for the option:
<label><input type="checkbox" class="food-option" data-kcals="100" value="scrambledEggs" />Scrambled Eggs</label>
<label><input type="checkbox" class="food-option" data-kcals="200" value="bacon" />Bacon</label>
<p id="output"><span>0</span>kcal</p>
Then you can use jQuery to attach the event and total up all the checked values and display them:
$('.food-option').change(function() {
var totalKcals = 0;
$('.food-option:checked').each(function() {
totalKcals += parseInt($(this).data('kcals'), 10);
});
$('#output span').text(totalKcals);
});
Example fiddle
In your case you can use this code:
HTML
<input type="checkbox" value="scrambledEggs" data-kcal="100">scrambledEggs</input>
<input type="checkbox" value="bacon" data-kcal="200">bacon</input>
<p id="output"> 0 kcal</p>
it have data-kcal tag which is container for your kcal value.
JS
var result = 0;
$('input[type="checkbox"]').on("change", function() {
if($(this).attr('checked'))
{
result += parseInt($(this).attr("data-kcal"));
}else{
result -= ($(this).attr("data-kcal"));
}
$("#output").text(result + " kcal");
});
Also you can check how it works on this jsFiddle.
Your HTML should be like below
<input type='checkbox' value="100">Scrambled Eggs </input>
<input type='checkbox' value="200"> Bacon </input>
<p id="output">0kcal </p>
Then you better use JQuery, less code written, more readability. The code below will achieve your needs.
$('input[type=checkbox]').change(function (e) { //This will trigger every check/uncheck event for any input of type CheckBox.
var res = 0;
$('input[type=checkbox]:checked').each(function() { //Loop through every checked checkbox.
res += parseInt($(this).val()); //Sum it's value.
});
$('#output').text(res); //Add the final result to your span.
});
Demo
Pass the element that is clicked into the function...
HTML
<input type=checkbox onchange="myFunction(this, 200)" value="bacon">Bacon</input>
JAVASCRIPT
function myFunction(element, value) {
console.log(element.checked);
}
Check this JSFiddle for a demo.
Better way of doing it is like this...
HTML
<div id="checkboxes">
<input type=checkbox value="bacon">Bacon</input>
<input type=checkbox value="Other">Other</input>
</div>
<p id="output">0kcal</p>
JAVASCRIPT
var checkboxes = document.getElementById("checkboxes");
checkboxes.onchange = function (e) {
alert("Target: " + e.target.value + " Checked: " + e.target.checked);
};
See this fiddle for a demo.

How to select a input field in next TD with Jquery?

I want to select a input field in next TD with Jquery. I can not use ID or class because the table's row can be add or removed.
like ,
<tr>
<td><input type='text' name='price[]' onkeyup = 'getTest(this)' /> </td>
<td><input type='text' name='qty[]' onkeyup = 'getPrice(this)' value='1' /> </td>
<td><input type='text' name='amount[]' /> </td>
</tr>
function getTest(obj){
//I want to select qty[] and amount[]
}
function getPrice(obj){
//I want to select price[] and amount[]
}
anybody know how to select the input fields, please help~!
Thanks
working demo of your expected behavior of your webpage.
Chinmayee's answer is much better than this one, but if you don't want to change any of your HTML mark-up, you can simply drop this into your JavaScript and it will work:
function getTest(obj) {
var tr = $(obj).closest('tr');
var qty = tr.find('input[name="qty[]"]');
var amount = tr.find('input[name="amount[]"]');
console.log('qty: ' + qty.val());
console.log('amount: ' + amount.val());
}
function getPrice(obj) {
var tr = $(obj).closest('tr');
var price = tr.find('input[name="price[]"]');
var amount = tr.find('input[name="amount[]"]');
console.log('price: ' + price.val());
console.log('amount: ' + amount.val());
}
But the reason why Chinmayee's answer is better than mine is because it uses unobtrusive JavaScript, and it also uses event delegation, so it will perform better.
Here's a possible solution for your problem (assuming you want amount to be price * qty):
$(document).ready(function(){
$('[name="price[]"], [name="qty[]"]').live('keyup', function(){
var inputs = $(this).closest('tr').find('input');
$(inputs[2]).val($(inputs[0]).val()*$(inputs[1]).val());
});
});
Your getTest() and getPrice() methods are no longer required with this solution and you can also drop the onkeyup="..." attributes on the input elements.
See here for a working demo.

Categories

Resources