each function jquery don't work - javascript

hi I've this html code
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/sunny/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<link href="stile.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
</head>
<body>
<form action="">
<div>
<div style="float:left; margin-right:3%">XXX</div>
<div>
<input type="text" name="price" id="price" value="2">
</div>
<div style="float:left; margin-right:3%">
<input type="button" name="button" id="button" value="button">
</div>
</div>
<div>
<div style="float:left; margin-right:3%">YYY</div>
<div>
<input type="text" name="price" id="price" value="3">
</div>
<div style="float:left; margin-right:3%">
<input type="button" name="button" id="button" value="button">
</div>
</div>
<div id="total"></div>
<script src="js/mine.js"></script>
</form>
</body>
</html>
and the follow js code in the file mine.js
$("#button").each(function() {
var sum = 0;
$('#price').each(function() {
sum += Number($(this).val());
});
$('#total').text(sum);
});
I'd like that when I click on button in the div id total it gives me the value of the field price.
So if I click on the first submit button it gives me the value 2 but if after I click on the second button it doesnt do the sum (2+3=5)

You should use class instead of id as jquery id selector (#) only returns one element
https://api.jquery.com/id-selector/
For id selectors, jQuery uses the JavaScript function
document.getElementById(), which is extremely efficient. When another
selector is attached to the id selector, such as h2#pageTitle, jQuery
performs an additional check before identifying the element as a
match.
Calling jQuery() (or $()) with an id selector as its argument will
return a jQuery object containing a collection of either zero or one
DOM element.
Inputs would be
<input type="text" name="price" class="price" value="2">
<input type="button" name="button" class="button" value="button">
In the case of total you can leave the id as you would have one final total
So your code would be something like this
$(".button").each(function() {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#total').text(sum);
});
UPDATE :
If you use this code and click first button it would give 2 and then the other one it would give 5. You can try disabling click handler in order to prevent from adding a second time.
$(document).on("click", ".button", function()
{
var sum = Number($('#total').text());
sum += Number($(this).closest("div").parent().find('.price').val());
$('#total').text(sum);
});
Addenda : Quantity input that increases each time button is pressed
<div>
<input type="text" name="quantity" class="quantity" value="0">
<input type="button" class="add-quantity">
</div>
$(document).on("click", ".add-quantity", function()
{
var input = $(this).closest("div").find(".quantity");
var currentVal = parseInt(input.val());
$(input).val(currentVal+1);
});

So looking at your code, you've got the following:
<input type="button" name="button" id="button" value="button"></div>
<div><input type="text" name="price" id="price" value="2"></div>
<input type="button" name="button" id="button" value="button"></div>
<div><input type="text" name="price" id="price" value="3"></div>
You've got button and id set twice as id's and you should have unique id's, so when you're check for each element use class= instead of id=.
So if you was to make that change, they would look like the following:
<input type="button" name="button" class="button" value="button"></div>
<div><input type="text" name="price" class="price" value="2"></div>
<input type="button" name="button" class="button" value="button"></div>
<div><input type="text" name="price" class="price" value="3"></div>
Then you would use $('.button') and $('.price') instead of $('#button') and $('#price') for the selectors in JQuery.
I've taken your fiddle and updated it.
Check the following:
JSFIDDLE
UPDATE
After reading your comment, i've updated my jsfiddle and you can now click the two buttons and then have the answer add up to (5)
The reason it was adding up to (5) straight away without you clicking the buttons was because it was doing the .each instead of you having to click the buttons yourself.
So to do this i've used two different classes for the buttons and inputs so they would like the following:
<input type="button" name="button" class="button" value="button"></div>
<div><input type="text" name="price" class="price" value="2"></div>
<input type="button" name="button" class="button1" value="button"></div>
<div><input type="text" name="price" class="price1" value="3"></div>
UPDATED JSFIDDLE
Every click will keep adding the value on to the total number because there no validation to tell the click to stop once it's added up to (5)
UPDATE USING ONE BUTTON
You could even do this, instead of having two buttons, you could just have one button which goes through each of the inputs and adds up the total.
for example:
JSFIDDLE EXAMPLE WITH ONE BUTTON
UPDATE USING TWO BUTTON (Same class names and Validation for 5)
So in the following update (example) it will show you how to get both values using the same class names for both buttons and inputs. It will also show you how to add little validation to stop the adding up once you have 5. So you can't go over 5 (Change it how you like).
JSFIDDLE WITH TWO BUTTONS AND LITTLE VALIDATION

Related

Calculating two fields in a form using JavaScript with a submit button and reset button

Here the code that I made and not working looking to see how I would get my sum into the result field, Also looking how to make a reset button to clear all the text from the fields.
JSBin.
<html>
<head>
<script>
function addition() {
var x = +document.getElementById('num1').value;
var y = +document.getElementById('num2').value;
document.getElementById('result').value = x + y;
document.result.submit()
}
function reset() {}
</script>
</head>
<body>
<header>
<h1>Calculator Using Forms & JavaScript</h1>
</header>
<form>
Number 1:
<input type="number" id="num1" value="0" autofocus>
<br> Number 2:
<input type="number" id="num2" value="0">
<br> Result:
<input type="text" id="result" value="0" readonly>
<br>
</form>
<input type="button" onclick="addition()" value="addition">
</body>
</html>
Why do you want to submit the form?
You can use document.forms. to access the form.
Try this:
<html>
<head>
<script>
function addition() {
var x = +document.getElementById('num1').value;
var y = +document.getElementById('num2').value;
document.getElementById('result').value = x + y;
document.forms.calculator.submit()
}
function reset() {
document.forms.calculator.reset();
}
</script>
</head>
<body>
<header>
<h1>Calculator Using Forms & JavaScript</h1>
</header>
<form name="calculator">
Number 1:
<input type="number" id="num1" value="0" autofocus>
<br> Number 2:
<input type="number" id="num2" value="0">
<br> Result:
<input type="text" id="result" value="0" readonly>
<br>
</form>
<input type="button" onclick="addition()" value="addition">
<input type="button" onclick="reset()" value="reset">
</body>
</html>
Do you want this one?
jsbin
<html>
<head>
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<script>
function addition() {
var x = +document.getElementById('num1').value;
var y = +document.getElementById('num2').value;
document.getElementById('result').value = x + y;
//document.result.submit()
//if you want use submit, use this code. if only see the result, don't use this
//Submit is receive data, so you can't see a result.
//document.getElementById('formId').submit();
//jquery submit
//$("form")[0].submit();
}
function reset() {
//no jquery
document.getElementById('formId').reset();
//jquery
//$("form")[0].reset();
}
</script>
</head>
<body>
<header>
<h1>Calculator Using Forms & JavaScript</h1>
</header>
<form id="formId">
Number 1:
<input type="number" id="num1" value="0" autofocus>
<br> Number 2:
<input type="number" id="num2" value="0">
<br> Result:
<input type="text" id="result" value="0" readonly>
<br>
</form>
<input type="button" onclick="addition()" value="addition">
<input type="button" onclick="reset()" value="reset">
</body>
</html>
Note that forms can be submitted without clicking the submit button, so if you want something to happen on submit, attach a listener to the form's submit handler. To reset a form only requires a reset button, no code.
Form controls must have a name to be successful and submit their value with the form, and you can pass a reference to the form using this from the listener so you don't need to use getElementById.
Implementing the above significantly reduces the amount of code required.
In the following, the submit listener returns false so prevents the form from submitting. If you want the form to submit, just remove the return statement from the in–line listener:
function addition(form) {
form.result.value = +form.num1.value + +form.num2.value;
}
<form name="calculator" onsubmit="addition(this); return false;">
Number 1:
<input type="number" name="num1" value="0" autofocus>
<br> Number 2:
<input type="number" name="num2" value="0">
<br> Result:
<input type="text" name="result" value="0" readonly>
<br>
<input type="submit" value="Submit form">
<input type="reset">
</form>
You may not want to submit the form at all, in that case you can make the submit button a plain button and call the function from there, but remember to stop the form submitting otherwise.
just give an id to the form and in your reset function, just do
document.getElementById("myForm").reset();
updates:
according to ROBG's comments, you don't need to bind a function to the button.
you can simply add a
<input type="reset">
to reset all fields of the form, and if the button is out the form, you can do
<input form="formID" type="reset">
to associate to specific form.

Cloning Checkboxes with different names

For better understanding what I want to do, here is a screenshot
I want to be able to submit whether checkboxes are checked or not. For this I used the trick to have hidden input fields, because otherwise unchecked boxes are not submitted. What I want to do now is to give pairs (one hidden, one checkbox) the same name, but each pair a different name. I tried quite a bit with javascript and jQuery but could not figure out how to get this done. The "+" Button is for adding more Checkboxes, the "-" Button is for deleting them again.
<html>
<head>
<title>test</title>
<script type="text/javascript">
function clone(button, objid)
{
tmpvalue = document.test.elements['param[]'][1].value;
document.test.elements['param[]'][1].value = '';
var clone_me = document.getElementById(objid).firstChild.cloneNode(true);
button.parentNode.insertBefore(clone_me, button);
document.test.elements['param[]'][1].value = tmpvalue;
}
function remove_this(objLink)
{
objLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(objLink.parentNode.parentNode.parentNode.parentNode);
}
</script>
</head>
<body>
<form name="test" method="post" action="test2.php">
<input name="param[0]" value="0" type="hidden">
<div id="hidden" style="visibility:hidden; display:none">
<div id="table"><table>
<tr><td>
<input name="param[]" type='hidden' value="0">
Parameter: <input name="param[]" type="checkbox" value="1">
</td>
<td>
<span style="margin-left:2em;"></span><input value="-" onclick="javascript:remove_this(this)" type="button">
</td>
</tr>
</table></div>
</div>
<div>
<input style="margin-top:2em;" value="+" onclick="javascript:clone(this, 'table');" type="button">
<button type="submit" name="sent">Submit</button>
</div>
</form>
</body>
</html>
So it would actually be nice to have some sort of counter like this:
<input name="param[i]" type='hidden' value="0">
Parameter: <input name="param[i]" type="checkbox" value="1">
Thanks for your help!
What about giving your checkboxes a class (for example "checkClass") and then scan all elements with this class using a jQuery? Like so..
// instead of $('button[type="submit"]') give your button an ID and use # selector
$('button[type="submit"]').click(function(){
//lets get all checkboxes..
$('.checkClass').each(function(){
// get their checked status
var checked = $(this).is(':checked');
// ..and do whatever you need here..
});
});
In terms of adding a new row on "plus" button click. Try considering the jquery "Append" method. Like so..
$('#plusButtonId').click(function(){
var rowHtml = '<tr><td>Parameter: <input name="param[]" type="checkbox" class="checkClass" value="1"></td><td><input value="-" type="button" class="remButton"></td></tr>';
$('#table').append(rowHtml);
});
..then use the ".remButton" selector and add a click event that will remove that tr element.
and last but not least - this is a great example why to start with AngularJS. It would be just one controller, a div with "ng-repeat" and a few methods. Try it ;)

jQuery remove selected element, dynamically generated

I have a form and I can dynamically add more lines but if I try to remove a specific line it does not work, however the first line gets removed with no problem.
Here is the html:
<form class="order-form">
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line">
<img alt="remove" src="img/close.png" />
<input class="input-text" name="product-code" type="text" placeholder="Product Code" ></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product"></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<div id="product-btn">
<input name="btn-add-line" type="button" value="Add new line"></input>
<input name="btn-update" type="button" value="Update"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">£</label>
<input class="input-text" name="order-info" type="text" placeholder="Order total" ></input>
</div>
</form>
The jQuery code I have tried:
$(".btn-close").on("click", function(e){
$(e.currentTarget).parent().remove();
});
I've also Tried
$(e.currentTarget).parents("div.product-lines).next("div.product-line).remove();
Any help would be most appreciated, also a explanation would be very helpful for me to learn.
Try something like
$(".product-lines").on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
You cannot attach events to objects that are not currently on page (lines).
You have to attach click event on product-lines object and when it is clicked you delegate event to "closest" product-line object!
You will need to changed the jQuery slightly to allow for Event Delegation. This means all elements added in future will get the event attached to them too.
$(document).on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
$('body').on('click','button id/class',function(){
$(e.currentTarget).parent().remove();
});
but if u use this code it will remove <div class="product-line">...</div>
why you want to remove this div.
i dont get your question very well. Explain in details and step by step .

JAVASCRIPT + HTML Button Value with getElements

I don't want to pass the value to the function, I want it to find the value itself.
<script type="text/javascript">
function add(buttonNum)
{
var elements = document.getElementsByTagName("button");
alert(document.myform.elements[buttonNum].value);
}
</script>
<form name="myform">
<input type="button" value="q" onclick="add(0)"/>
<input type="button" value="w" onclick="add(1)"/>
<input type="button" value="e" onclick="add(2)"/>
<input type="button" value="r" onclick="add(3)"/>
<input type="button" value="t" onclick="add(4)"/>
<input type="button" value="y" onclick="add(5)"/>
</form>
If I wanted to click on a button and display the value of the button into lets say a div; I don't want to code every button with an onclick(passing a parameter).
What approaches do I need to take? Something tells me that I need to get the length, run a for loop, and attach a handler. I'm just not sure on where to start.
simply pass this as parameter so that you can access all the attributes of the element but here only value:
<script type="text/javascript">
function add(elem)
{
alert(elem.value);
}
</script>
<form name="myform">
<input type="button" value="q" onclick="add(this)"/>
<input type="button" value="w" onclick="add(this)"/>
<input type="button" value="e" onclick="add(this)"/>
<input type="button" value="r" onclick="add(this)"/>
<input type="button" value="t" onclick="add(this)"/>
<input type="button" value="y" onclick="add(this)"/>
</form>
Compare:
getElementsByTagName("button");
<input>
You are getting the wrong element type.
If I wanted to click on a button and display the value of the button into lets say a div; I don't want to code every button with an onclick(passing a parameter).
Use addEventListener. You can identify the element clicked with event.target
e.g.
addEventListener('click', function (evt) {
if (evt.target.type == "button") {
alert(evt.target.value);
}
});

Triggering events in html using same button

I want to trigger an event with a button that changes the visibility of a set of elements (inputs of type text and button) from hidden to visible. Now everytime I click on the triggering button, I want a new set of the same elements to appear on a new line. How can that be done? Here is a snippet of the code:
<script type="text/javascript">
function generatenew()
{
document.add.property1.style.visibility="visible";
document.add.button2.style.visibility="visible";
document.add.button3.style.visibility="visible";
document.add.button4.style.visibility="visible";
}
</script>
</head>
<body>
<form name='add' method="post" action="">
<div id="div"></div>
<input type="button" value="+Add" onclick="generatenew();">
<input type="button" value="Edit" name="button2" style="visibility:hidden">
<input type="text" style="visibility:hidden" size="50" name="property1" placeholder="<street> <city> <ZIP> <country> <lockunitID>">
<input type="button" style="visibility:hidden" name="button3" value="open main door">
<input type="button" style="visibility:hidden" name="button4" value="open apartment door">
<div id="abc"><input type="button" value="save"></div>
If I well understood your question, all you have to do is putting a function that is triggered by an onClick event, (element.onClick=function();) You put all your input type tags in the function, and then you end your function bay calling appendChild method so that each click triggers the display of your elements.

Categories

Resources