Compare two variables with generated numbers - javascript

Currently I learn the curve of PHP and for first time trying to make AJAX request to my PHP script. I got cart in my own written shop for learning purposes, it generates button and input field with same "data-id" attributes for each position. And of course, input field got "value" attribute with current amount of products.
Code:
Jquery:
$(document).ready(function() {
$(".btn").click(function () {
var id = $(this).attr("data-id");
var idInput = $(".field").attr("data-id");
var value = $(".field").attr("value");
if (id === idInput) {
$.post("/cart/addAjax/" + id, {}, function (data) {
$("#cart-count").html(data);
});
$.post("/cart/addAjax/" + value, {});
return false;
} else {}
});
});
Example of input of PHP generated HTML:
<input class="field" data-id="3" type="number" value="23">
<button class="btn" data-id="3">Quantity</button>
<input class="field" data-id="14" type="number" value="3">
<button class="btn" data-id="14">Quantity</button>
<input class="field" data-id="17" type="number" value="2">
<button class="btn" data-id="17">Quantity</button>
<input class="field" data-id="18" type="number" value="8">
<button class="btn" data-id="18">Quantity</button>
<input class="field" data-id="19" type="number" value="10">
<button class="btn" data-id="19">Quantity</button>
I want Jquery script to compare input/button "data-id" attributes and send "value" of selected "data-id" attribute request to PHP side, but don't know how to tell script get "value" from selected "data-id", guess its the reason why its POST successfully only for first generated product in cart, for the rest products script doesn't work. Can someone enlighten me how to achieve this? Thanks in advice.

You need to structor your html a little better.
I made some changes to the html and put each btn and field under a div.
This will make things easer to find the selected input by its btn click.
Read the comment to understand.
$(document).ready(function() {
$(".btn").click(function () {
var id = $(this).attr("data-id");
// now go to the selected btn Parent, and then find the .field
// there you are sure its the right field becouse both the button
// and the field is containe under one div{Parent}
var idInput = $(this).parent().find(".field")
console.clear();
console.log("you Selected id " +id + " and its value is " + idInput.val())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="field" data-id="3" type="number" value="23">
<button class="btn" data-id="3">Quantity</button>
</div>
<div>
<input class="field" data-id="14" type="number" value="3">
<button class="btn" data-id="14">Quantity</button>
</div>
<div>
<input class="field" data-id="17" type="number" value="2">
<button class="btn" data-id="17">Quantity</button>
</div>
<div>
<input class="field" data-id="18" type="number" value="8">
<button class="btn" data-id="18">Quantity</button>
<div>
<input class="field" data-id="19" type="number" value="10">
<button class="btn" data-id="19">Quantity</button>
</div>

$('button').on('click',function(){
var data = $(this).data('id');
var url = 'your php file';
$.post(url,data,function(rdata){
//do whatever yo want with returned data
});
});

Related

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

update textfield when radio button is selected and button is pressed Javascript

I have 4 radio buttons, when I select one, I want the default value of the quantity(addNumberOfItems) to be 1.
when a radio button is selected it should update a textfield that holds the quantity. Afterwards I have a button to add to the order. The problem is when I click addToOrderBtn and try and increase the quantity on the textfield(I replace the default 1 with 2 or 3) it always sets it back to 1.
My textfield that keep track of Total items(totalItems), should add what I input into addNumbersOfItems.
I tried to update the value of addNumberOfItems when the button is clicked. but its still set to default value.
Javascipt only please.
Thank you!
Code pen: http://codepen.io/anon/pen/LpJqgj
var addNumberOfItems = document.getElementById("numberOfItems");
var addToOrderBtn = document.getElementById("addToOrder");
var totalItems = document.getElementById("items");
var totalPrice = document.getElementById("total");
if (selected == "Classic" && foodOptionChecked1 == true) {
addNumberOfItems.value = 1;
};
addToOrderBtn.onclick = function() {
document.getElementById('numberOfItems').value = addNumberOfItems.value;
totalItems.value = addNumberOfItems.value;
totalPrice.value = foodClassic[0].smallPrice;
addNumberOfItems.value = "";
};
HTML
<fieldset class="form1 hide" id="choices">
<legend> your Choices </legend>
<p style="margin-left:25%">Which one would you like?</p>
<form style="float: right" id="selectSize">
<input type="radio" id="food1" name="size" value=""><label id="foodLabel1">food1</label>
<br>
<input type="radio" id="food2" name="size" value=""><label id="foodLabel2">food2</label>
<br>
<input type="radio" id="food3" name="size" value=""><label id="foodLabel3">food3</label>
<br>
<input type="radio" id="food4" name="size" value=""><label id="foodLabel4">food4</label>
<input type="text" id="numberOfItems" name="" value="">
<button type="button" id="addToOrder">Add to order</button>
<button type="button">Remove last item</button>
</form>
<p style="margin-top: 15%; margin-left:25%"> Extras! </p>
<p style="margin-top: 11%; margin-left:25%"> How many? </p>
</fieldset>
<fieldset class="form1 hide" id="orderStatus">
<legend> Order Status </legend>
<form>
Items<input type="text" name="" id="items">
Total<input type="text" name="" id="total">
<button type="button">Order Now</button>
<button type="button">Cancel</button>
</form>
</fieldset>
This is because inside getOrder() this line addNumberOfItems.value = 1; make quantity to 1 when you change quantity value
try following code in your getOrder() where you setting default value will solve you problem of quality reset
if (selected == "Classic" && foodOptionChecked1 == true) {
if(addNumberOfItems.value.length == 0)
addNumberOfItems.value = 1;
}
};
but sill i am unable to find why getOrder() call after changing the quality value might be because of code in your main.js

each function jquery don't work

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

How to have multiple radio buttons with different functionality?

I am working on a project in which I need to make an HTML page with couple of radio buttons.
First radio button is, INSERT. As soon as I click INSERT radio button, I would like to show three text box just below the INSERT radio button. First textbox is datacenter, second textbox is node and third textbox is data.
Second radio button is, UPDATE. As soon as I click UPDATE radio button, I would like to show same above three text box just below the UPDATE radio button.
Third radio button is, DELETE. As soon as I click DELETE radio button, I would like to show only one text box just below the DELETE radio button. In this one text box will be node.
Fourth radio button is, PROCESS. As soon as I click PROCESS radio button, I would like to show four text box just below the PROCESS radio button. In this first textbox will be datacenter, second textbox will be node, third textbox will be conf and fourth textbox will be data.
I am able to make first two radio button work (insert and update) but somehow I am not able to understand how do I make last two radio button work.
Below is my HTML
<form method="post" action="testOperation">
<input type="hidden" name="name" id="dynamicName">
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div>
<br/>
<input type="submit">
</form>
Below is my jquery -
$(document).ready(function(){
$(".changeAction").on("click", function(){
$('.changeable').html('')
var divId = $(this).attr("div-id");
$("#dynamicName").val(divId);
divId = "#"+divId;
var myInput = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" /> <label for="Node"> Node </label> <input type="text" name="node" size="20" /> <label for="Data"> Data </label> <input type="text" name="data" size="100"/>'
$(divId).html(myInput);
})
})
And here is my jsfiddle. It will be of great help if anyone can provide any jsfiddle example?
try this code in javascript part,
var datacenter = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" />';
var node = '<label for="Node"> Node </label> <input type="text" name="node" size="20" />';
var data = '<label for="Data"> Data </label> <input type="text" name="data" size="100"/>';
var config = '<label for="Config"> Config </label> <input type="text" name="config" size="100"/>';
$(".changeAction").on("click", function () {
var divId = $(this).attr("div-id");
$('.changeable').html('');
$("#dynamicName").val(divId);
switch (divId) {
case 'insert':
//insert stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'update':
//update stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'Delete':
//Delete stuff goes here!!
divId = "#" + divId;
var myInput = node;
$(divId).html(myInput);
break;
case 'process':
//process stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + config + data;
$(divId).html(myInput);
break;
}
});
SEE FIDDLE DEMO
Change your html code to this
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div><br/>
<input class="changeAction" type="radio" name="tt" value="Delete" div-id="delete"/> Delete
<div id="delete" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Process" div-id="process"/> Process
<div id="process" class="changeable"></div>
<br/>
<input type="submit">
</form>

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);
}
});

Categories

Resources