Extract from JS to url - javascript

But I would be interested in how I can send this result from the js as a get
<form method="GET" action="order2.php">
<input type="checkbox" name="obj" price="5" value="1" >5
<input type="checkbox" name="obj" price="15" value="2">15
<input type="checkbox" name="obj" price="20" value="3">20
<input type="submit" value="send">
<div id="test"></div>
<script type="text/javascript">
$(":input").change(function() {
var values = $('input:checked').map(function () {
return $(this).attr('price');;
}).get();
var total = 0;
$.each(values,function() {
total += parseFloat(this);
});
$("#test").text(total);
});
</script>
</form>
When I select inputs 1 and 2 so that the result is in url order2.php?price=20

$(":input").change(function() {
var values = $('input:checked').map(function () {
return $(this).attr('price');;
}).get();
var total = 0;
$.each(values,function() {
total += parseFloat(this);
});
$("#test").text(total);
$('form').attr('action', 'order2.php?price=' + total);
console.log ( $('form').attr('action') ) ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
But I would be interested in how I can send this result from the js as a get
When I select inputs 1 and 2 so that the result is in url order2.php?price=20
<form method="GET" action="order2.php">
<input type="checkbox" name="obj" price="5" value="1" >5
<input type="checkbox" name="obj" price="15" value="2">15
<input type="checkbox" name="obj" price="20" value="3">20
<input type="submit" value="send">
<div id="test"></div>
</form>

From your description that when you select option 1 and 2, you have the sum of the options as the price. I'll break this down into steps:
You have to sum the selected options
Construct your query param
Use Ajax to make your get request
This guides through how to do Ajax tutorial for post and get.
Hope this helps...

When a form submits, it will append all of it's inputs to the query string or post data (depending on the request type). A very simple way to add another field parameter called price with the sum is just to add a hidden input and update that dynamically with the sum.
Notice that I remove the name attribute from the checkboxes. I did this so that they wouldn't be send on the form submission.
I also replaced your forEach with a reduce() as it is more functional and you can chain it with the map()
$("#myform input").change(function() {
var total = $('input:checked').map(function () {
return $(this).attr('price');
}).get().reduce(function(sum, value) {
return sum + parseFloat(value);
}, 0);
$(".price").val(total);
$(".price").html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="order2.php">
<input type="checkbox" price="5" value="1" >5
<input type="checkbox" price="15" value="2">15
<input type="checkbox" price="20" value="3">20
<input type="hidden" name="price" class="price"/>
<input type="submit" value="send">
</form>
<span class="price"></span>

Related

get data-attr from a form input checkbox using JS

If someone puts a checkmark, I want to get the data-price attribute. Nothing is appearing in the console.log. I tried using .prop('checked'), .data('checked'), and .attr('checked'). I am assuming something is wrong with the Syntax?
This articleGet data-price jquery code as below does not seem to work:
$(document).ready(function(){
if $('#pizzaOption').click(function() {
var price=$(this).data('price');
console.log(price);
});
<form action="" id="pizzaOption" data-price="5">Large Pizza <br>
<input type="checkbox" value="sausage">Sausage<br>
<input type="checkbox" value="pepperoni">Pepperoni<br>
<input type="checkbox" value="mushrooms">Mushrooms<br>
<input type="submit" value="Submit">
</form>
Used this article to no success. https://medium.com/js-dojo/check-if-a-checkbox-is-checked-with-jquery-2843f97d4954 Code is below:
<script type= text/javascript>
$(document).ready(function() {
if ($('input[type=checkbox]').attr('checked') {
var price=$(this).data('price');
console.log(price);
}
}
</script>
You have lots of mistake in your code.
$(document).ready(function(){ {
if $('#pizzaOption').click(function() {
var price=$(this).data('price');
console.log(price);
});
You have { { in callback function of $(document).ready() and it is not closed with }); And you have if in your click event which results syntax error.
In your second code
<script type= text/javascript>
$(document).ready(function() {
if ($('input[type=checkbox]').attr('checked') {
var price=$(this).data('price');
console.log(price);
}
}
</script>
You have checked the attr('checked') but there is no event binded on it and will always result false because no checkbox is checked onload event and $(this).data('price'); is undefined because data-price on the parent element of the clicked checkbox.
And you have click event on '#pizzaOption' according to your question you need to bind the click event on checkbox here is an example:
$(document).ready(function(){
$('#pizzaOption>input[type="checkbox"]').click(function() {
var price=$(this).closest("#pizzaOption").data('price');
console.log(price);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="pizzaOption" data-price="5">Large Pizza <br>
<input type="checkbox" value="sausage">Sausage<br>
<input type="checkbox" value="pepperoni">Pepperoni<br>
<input type="checkbox" value="mushrooms">Mushrooms<br>
<input type="submit" value="Submit">
</form>
Another example:
$(document).ready(function(){
$('#pizzaOption>input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
var price=$(this).closest("#pizzaOption").data('price');
console.log(price);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="pizzaOption" data-price="5">Large Pizza <br>
<input type="checkbox" value="sausage">Sausage<br>
<input type="checkbox" value="pepperoni">Pepperoni<br>
<input type="checkbox" value="mushrooms">Mushrooms<br>
<input type="submit" value="Submit">
</form>
<form action="" id="pizzaOptions" data-price="5">Large Pizza <br>
<input type="checkbox" value="sausage">Sausage<br>
<input type="checkbox" value="pepperoni">Pepperoni<br>
<input type="checkbox" value="mushrooms">Mushrooms<br>
<input type="submit" value="Submit">
</form>
<script>
// wait until document is ready
$(document).ready(function(){
// For every checkbox checked inside form
$('#pizzaOptions input[type="checkbox"]').click(function(){
// display value
console.log($(this).val())
// now if you want to get the price you should
console.log($('#pizzaOptions').attr('data-price'))
})
})

Choosing among radio buttons and Text Field

I have 2 radio buttons. All of them have different values. I also have one text field, in case I need a different value, I can enter that value on that text field.
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="https://example.com/fee/25"> $25
<input type="radio" name="url" value="https://example.com/fee/50"> $50
<input type="submit" value="Submit">
</form>
and here is the Javascript I've found to make radio buttons working
<script type="text/javascript">
function doSubmit(form) {
var urls = form['url'];
var i = urls && urls.length;
while (i--) {
if (urls[i].checked) {
window.location = urls[i].value;
}
}
document.getElementById("amount").value;
return false;
}
</script>
I have one text field:
<input type="text" name="amount" size="10" id="amount" value="">
Ok. If the amount is entered, then I need to use this code:
document.getElementById("amount").value
But how to make it working with radio buttons? I have created this JS code:
<script type="text/javascript">
var link = "https://example.com/fee/";
var input= document.getElementById('amount');
input.onchange=input.onkeyup= function() {
link.search= encodeURIComponent(input.value);
};
</script>
What I'm doing wrong? Thanks in advance for your time. I love and enjoy learning from experts.
I would create a separate radio button for the text input:
var options = Array.from(document.querySelectorAll("[name=url]"));
amount.addEventListener('focus', function() {
options[0].checked = true; // If textbox gets focus, check that radio button
});
options[0].addEventListener('change', function() {
amount.focus(); // if first radio button gets checked, focus on textbox.
});
function doSubmit(form) {
// get checked value, replace empty value with input text
var value = options.find( option => option.checked ).value || amount.value;
window.location = "https://example.com/fee/" + value;
return false;
};
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="" checked>
$<input type="text" name="amount" size="5" id="amount" value="" >
<input type="radio" name="url" value="25"> $25
<input type="radio" name="url" value="50"> $50
<input type="submit" value="Submit">
</form>
Instead of using the url as the value for the radio buttons, consider using the value you wish to pass to the url:
function doSubmit(form) {
var endpoint = "https://example.com/fee/";
// gets the values of input elements that were selected
var checkedValues = Array.from(form.amounts)
.filter(radio => radio.checked)
.map(radio => radio.value);
// if a radio button was checked, use its value
// otherwise, use the value in the text field
var amount = checkedValues.length ?
checkedValues[0] : form.amount.value;
console.log('redirecting to: ', endpoint + amount);
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>
Edit: Wow I completely forgot you could use the :checked attribute as a css selector. In this case, the code becomes quite simple:
function doSubmit(form) {
// select checked inputs with the specified name attribute
var checkedRadio = document.querySelector('input[name="amounts"]:checked')
// if we have a radio button that is checked, use its value
// otherwise, use the text input's value
var amount = checkedRadio ? checkedRadio.value : form.amount.value;
window.location = 'https://example.com/fee/' + amount;
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>

With JQuery how can you make an array of inputs from checkboxes into one variable?

I would like to make the data from this jquery submit go into one variable that I can put into html. I am using the append button to add html to my form, but can't figure out how to make the data variable into an array of each check box value .
https://jsfiddle.net/soljohnston777/k5yc1y2a/2/
JQuery:
$(".checkboxadd").click(function(){
$('[id^="add_policies_checkbox"]').each(function(i, v){
//alert(this.value);
if($(v).prop('checked')){
var data=$(v).val();
$("#div_to_add_this_checkbox_value").append("<input type=hidden name='pnpID_instructions' value=\'"+data+"\' />P&P #'s: "+data+"");}
});
});//end ajaxifypolicies
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="add_policies_checkbox1"/>
<input type="checkbox" value="2" id="add_policies_checkbox2"/>
<input type="checkbox" value="3" id="add_policies_checkbox3"/>
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>
<div> Check mark all 3 then hit submit, What I want is the output like an array:<br>P&P #'s:1,2,3 <br> (and the hidden value="1,2,3")
</div>
To convert an array to a string you can use array.join(',').
$(".checkboxadd").click(function() {
var data = [];
$('[id^="add_policies_checkbox"]').each(function(i, v) {
if ($(v).prop('checked')) {
data.push($(v).val());
}
});
console.log(data);
$("#div_to_add_this_checkbox_value").html('P&P #s:' + data.join(',') + "<input type='hidden' name='pnpID_instructions' value='"+data.join(',')+"' />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="add_policies_checkbox1" />
<input type="checkbox" value="2" id="add_policies_checkbox2" />
<input type="checkbox" value="3" id="add_policies_checkbox3" />
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>

How to validate a form in jsp using javascript before submit

<form name="Details" method="post" action="insertData.jsp" onSubmit="return ValidateForm();">
<label> Name </label > <input type="text" name="name" id="test1" > </input>
<label> ID </label > <input type="text" name="id" id="test2" > </input>
<label> Time </label > <input type="text" name="time" id="test3" > </input>
<label> Latitude </label > <input type="text" name="latitude" id="test4" > </input>
<label> Longitude </label > <input type="text" name="longitude" id="test5" > </input>
<input type= " submit" id="test6" value="submit" > </input>
Validation code in js
function ValidateForm()
{
var uname=document.Detail.name;
if(alphanumeric(uname)){
}
return false;
}
function alphanumeric(uname){
var letter=/*[0-9a-zA-Z]+$/;
if(uname.value.match(letter)){
return true;
}
else{
aler("Enter both alpha and number");
uname.focus();
return false;
}
}
The above validation is to allow a textfield to accept both alphabets and numbers but not only numbers. Its returning false on a wrong input but still the data entered entered is submitted to the database. How to avoid this? what is wrong in my code?
I also want to validate form before submit. After every field is entered it should be validated and displayed if any error just below the field. How do i do it?
You could use a naming pattern for the Ids of hidden <span> tags that represent the form field error messages:
<form onsubmit="return ValidateForm(this);">
<p>
<input type="text" id="name" name="name">
<span style="display: none;" id="name-validation-message"></span>
</p>
</form>
<script>
function ValidateForm(form) {
if (!alphanumeric(form.elements.name)) {
var message = document.getElementById(form.elements.name.id + "-validation-message");
message.innerHTML = "Must be alphanumeric";
message.style.display = "";
}
}
</script>
The elements property on form objects is a key-value store where the keys are the values of the name attribute on the form fields, and the values are either a reference to a single form field DOM node, or a collection.
Consider the following HTML:
<form id="test">
<input type="text" name="foo">
<input type="checkbox" name="bar" value="1">
<input type="checkbox" name="bar" value="2">
<input type="checkbox" name="bar" value="3">
<input type="checkbox" name="bar" value="4">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
</form>
We have three unique form field name attribute values:
foo
bar
things[]
In JavaScript, we'll have the following object model:
var form = document.getElementById("test");
form.elements; // A collection of references to all form fields
form.elements.foo; // Reference to <input type="text" name="foo">
// A DOM node collection referencing all checkboxes whose name is "bar"
form.elements.bar;
form.elements.bar[0]; // First "bar" checkbox
form.elements.bar[1]; // Second "bar" checkbox
// A DOM node collection referencing all text boxes whose name is "things[]"
form.elements["things[]"];
form.elements["things[]"][0]; // First "things[]" textbox
form.elements["things[]"][1]; // Second "things[]" textbox
Many server side languages turn field names with square brackets into arrays. You can access those fields in JavaScript using the Array Notation (e.g. form.elements["bar"] instead of Dot Notation (e.g. form.elements.bar).
Hope the following code helps.
<HTML>
<HEAD>
<TITLE>Verifying User Data</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function checker()
{
var regExp1 = '/^(\d{1,2})\/(\d{1,2})\/(\d{2})$/' ;
var result1 = document.form1.text1.value.match(regExp1);
if (result1 == null || <*any other input doesnt satisfy the required format*>) {
alert("Sorry, that's not a valid date.");
document.form1.text1.focus(); // or document.<formname>.<element_name>.focus();
return;
} else {
document.form1.action="<NextPage.jsp>" ;
document.form1.method="GET"; // or "POST"
document.form1.submit();
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Verifying User Data</H1>
<FORM NAME="form1" >
Please enter a date:
<INPUT TYPE="TEXT" NAME="value1">
<INPUT TYPE="<sometype>" NAME="value2">
<INPUT TYPE="<sometype>" NAME="value3">
..
..
<INPUT TYPE="button" onclick="checker()">
</FORM>
</BODY>
Write another javascript on submit button like
<input type= " submit" id="test6" value="submit" onclick="return save();">
<script>
function save(){
document.form[0].submit;
}
</script>

enhance name attribute in a form

I have a form, and add dynamically fields to it. After adding the fields I want to enhance the name attribute in the way that this:
<form id="workshops" action="" method="post">
<input type="hidden" value="1" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
<input type="hidden" value="3" name="form-0-Workshops">
<input type="hidden" value="evening" name="form-0-Day">
<input type="hidden" value="3" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
</form>
Becomes:
<form id="workshops" action="" method="post">
<input type="hidden" value="1" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
<input type="hidden" value="3" name="form-1-Workshops">
<input type="hidden" value="evening" name="form-1-Day">
<input type="hidden" value="3" name="form-2-Workshops">
<input type="hidden" value="morning" name="form-2-Day">
</form>
I have this to start with but I don't make any progress.....
var forms = $('form#workshops input[name$="Workshops"]');
for (var i=0, formCount=forms.length; i<formCount; i++){
$('form#workshops input[name$="Workshops"]').each(function() {
//$(this) seems to be empty
});
}
Try using this:
// Get all the forms inputs
var $forms = $('form#workshops input[name$="Workshops"]');
// Loop through each form inputs
$forms.each(function () {
console.log($(this));
});
Your code keeps re-selecting things inside of a loop. Makes no sense.
Use each to your advantage, it gives you the index so there is no need to do the for loop. .
function rename (i) {
var parts = this.name.split("-");
parts[1] = i;
this.name = parts.join("-");
}
var form = $("#workshops");
form.find('input[name$="Workshops"]').each(rename);
form.find('input[name$="Day"]').each(rename);
Maybe just try :
$('#workshops input[name$="Workshops"]').each(function() { /*...*/ });
Please try the following code:
var forms_input = $('form#workshops input[name *="Workshops"]');
forms_input.each(function() {
console.log($(this))
});

Categories