jQuery or Javascript to parse querystring on submit - javascript

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.

The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});

A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>

I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel

Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

Related

Don't append if string already contains OnChange

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

how do I check dynamically generated radio input value

I have to generate multiple input fields dynamically for each time user clicks "add" button and I was successfully able to get them. Each contact should have this radio input field in different different name so I've created a name in an array form.
Here's what I have so far and I wonder how I'm supposed to get the radio value for each person:
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
options = '<p>Visit Type:
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Student" required>Student</label>
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$(options).fadeIn("slow").appendTo('.companion');
return false;
}
});
$('.c_visittype' + count).on('click', function(){
$('input:radio[name="c_visittype"]').attr('checked', 'checked');
});
Each person should get a choice of either 'student' or 'visitor' and I have to get this value for multiple persons whenever more person fields created.The reason why I put field's name as an array is to iterate it in the next page by php.
<script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
var options = '<p style="display: none">Visit Type:<label class="radio-inline"> <input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Student" required>Student</label> <label class="radio-inline"><input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$('.companion').append(options);
$(".companion p:last").fadeIn();
}
});
});
</script>
<button id="add">add</button>
<div class="companion">
</div>
$('input[name=c_visittype[]]:checked').val();
That's how you access the value of a checked radio button with jQuery.
var inputValues = [];
$('.c_visittype:checked').each(function() {
inputValues.push($(this).val());
});
// Your code using inputValues
For update on changes:
$(function() {
$('.c_visittype').click(function(){
// Insert code here
}
)});
Make sure to move the numbering from the class attribute to the name attribute (like it was, everything was part of the same set of options). Also, put the whole string on 1 line.

Storing / passing a variable to another function

I have a simple problem storing and passing a variable from one function to another. My script should work like this:
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="write()">
<p id="ag"></p>
If somebody enters a value in the input field "ip1" and presses the "check_button", the value should be stored in a variable. This variable should be written in the innerHTML of "ag" when the "write_button" is clicked.
This is my JS. I am aware that this cannot work, I just don't know how to do it properly. I found similar problems but the solution always seems to complex for a beginner like myself to understand. A very easy solution would be very much appreciated!
function check_text() {
var ui = document.getElementById('ip1').value;
}
function write() {
document.getElementById('ag').innerHTML = ui;
}
You should declare variable outside the function:
it must work
var ui = 0;
function check_text() {
ui = document.getElementById('ip1').value;
}
function writeL() {
document.getElementById('ag').innerHTML = ui;
}
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="writeL()">
<p id="ag"></p>
There are of course more than one way to process your value. The Snippet below uses the HTMLFormControlsCollection. Details are commented in the Snippet. BTW, I had to get rid of one of the buttons, it would probably hinder your understanding rather than aid it. It's better to visualize what's happening by watching the console.
SNIPPET
/***NOTE: Any comment having a pencil icon: ✎
|| means that the expression/statement is there...
||...to show an alternate way. Although they...
||...aren't used in the functions, they can be...
||...used instead of it's counterpart.
*/
function processData() {
// Reference the <form> by id or...
var form1 = document.getElementById('form1');
// ✎
/*1*/
console.log('1. This is ' + form1.id + '\n');
/*...or by HTMLFormControlsCollection...
||...reference <form> as the first <form>...
||...the .forms is an array-like object...
||...the [0] is the index indicating which...
||...<form> it's referring to. This is easily...
||...determined since there's only one <form>...
||...on the page.
*/
var formA = document.forms[0];
/*2*/
console.log('2. This is ' + formA.id + '\n');
// We'll continue using the HTMLFormControlsCollection
/* This is using previously declared formA to...
||...reference it's .elements property. The...
||...elements property is like the .forms...
||...except that it refers to a <form>'s...
||...field form elements like <input> and ...
||...<output>
*/
var formUI = formA.elements;
/*3*/
console.log('3. This is an ' + formUI + '\n');
// We can get the number of form control elements
var qty = formUI.length;
// ✎
/*4*/
console.log('4. form1 has ' + qty + ' form control elements\n');
/* Get the value of text1 by using the object formUI...
||...the name of <input>, and the .value property.
*/
var TXT1 = formUI.text1.value;
/*5*/
console.log('5. The value of text1 is ' + TXT1 + '\n');
/* We can get the same result by referencing <input>...
|| ...by it's index position in the formUI object...
|| This expression is getting the value of the first...
||...form field element of the <form> or formUI object
*/
var TXTA = formUI[0].value;
// ✎
/*6*/
console.log('6. The value of Text1 is still ' + TXTA + '\n');
/* Return the value of TXT1
|| This function returns a value, so it can be...
||...assigned to a var as a value and it can be...
||...passed through another function like a...
||...parameter.
*/
return TXT1;
}
/* This will pass a value...
||...reference the <output>...
||...and set <output> value to...
||...given value
*/
function displayData(value) {
var output1 = document.getElementById('output1');
output1.value = value;
}
/* When button1 is clicked...
||...store the return of processData() in a var...
||...then pass that var to displayData() function
*/
document.getElementById('button1').onclick = function(event) {
var VAL = processData();
displayData(VAL);
}
input {
font: inherit
}
<form id='form1' name='form1'>
<input type="text" id="text1" name='text1'>
<input type="button" value="display" id='button1'>
<br/>
<output id="output1" name='output1'></output>
</form>
You can do it easily with jQuery like this:
var enteredValue = "";
$("#check_button").on("click", function() {
enteredValue = $("#ip1").val();
});
$("#write_button").on("click", function() {
$('#store_value').html(enteredValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ip1" />
<input type="button" id="check_button" value="checking" />
<input type="button" id="write_button" value="write" />
<p id="store_value"></p>

Value of checkbox is [object HTMLInputElement]

I have two forms right next to each other.
This right here is Form one
<form>
<input type="radio" id="genderOne" name="genderOne" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
Form 2 is simply the same, with the difference that the IDs of the checkboxes are genderThree and genderFour and the name is genderTwo. The checkbox has also another name "ageCheckTwo".
Now I want, if everything is filled in correctly to open up a php.site with the parameters the user typed in.
Everything works, except for the second form, but only the gender.
This is the JavaScript-code for that part
if(document.getElementById('genderOne').checked || document.getElementById('genderTwo').checked)
{
if(document.getElementById('genderOne').checked)
{
var genderOne = $('#genderOne').val();
urlString += "&genderOne=" + genderOne;
}
if(document.getElementById('genderTwo').checked)
{
var genderTwo = $('#genderTwo').val();
urlString += "&genderOne=" + genderTwo;
}
}
if(document.getElementById('genderThree').checked || document.getElementById('genderFour').checked)
{
if(document.getElementById('genderThree').checked)
{
var genderOne = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderTwo = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
}
And just to be sure, this is the second form
<form>
<input type="radio" id="genderThree" name="genderTwo" value="Mann"><label for="genderThree">Maennlich</label>
<input type="radio" id="genderFour" name="genderTwo" value="Frau"><label for="genderFour">Weiblich</label><br><br>
<input type="checkbox" id="ageCheckTwo" id="ageCheckTwo" name="ageCheckTwo"><label for="ageCheckTwo">Ist er/sie ueber 18?</label>
</form>
But, the URL is now, when I checked all parameters like this:
http://localhost/mojoGerman/questions.php?nameOne=fdgh&nameTwo=hj&genderOne=Mann&genderTwo=[object HTMLInputElement]
While it should display the gender of the second person at the end. What am I doing wrong?
Simple typographic errors here:
if(document.getElementById('genderThree').checked)
{
var genderThree = $('#genderThree').val();
urlString += "&genderThree=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderFour = $('#genderFour').val();
urlString += "&genderFour=" + genderFour;
}
This is why cutting and pasting is a bad idea. Make yourself a simple function:
function addIfChecked(name) {
var val = $('#' + name).val();
return val ? "&" + name + "=" + encodeURIComponent(val) : '';
}
urlString += addIfChecked("genderOne") +
addIfChecked("genderTwo") +
addIfChecked("genderThree") +
addIfChecked("genderFour");
or something like that. Better yet, give the checkboxes a class so that you can find them with a selector and iterate over them via jQuery.
var genderOne = $('#genderThree').val(); // get value in genderThree here
urlString += "&genderTwo=" + genderThree;
Try this -
if(document.getElementById('genderThree').checked) {
var genderThree = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked) {
var genderFour = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
The issue is using the wrong variable names for genderThree and genderFour
But you could simplify the whole thing to
$('input[type="radio"][name^="gender"]:checked').each(function(){
urlString += '&' + this.name + '=' + this.value;
});
I have not understood completely what are you trying to do , but seeing at your code, I think It can be optimised by using different practice
<form>
<input type="radio" id="genderOne" name="genderOne[]" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne[]" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
If you want to have same key on your query string genderOne , you can explicity declare your name as array in the name attribute. On your php script you can get this value using GET method to obtain those values
//php
echo $_GET['genderOne'][0];//returns first checked gender value
echo $_GET['genderOne'][1];//returns 2nd checked gender value
You don't even need the javascript for this if I understood what you are trying to achieve.

Variable not updating

I have 2 files, my index and my JS file.
In my index I will have a form of input fields and my index file will be linked to my JS file.
In my JS file I will have a list of variables which will get their values from my index file input fields. I plan on then multiplying some of my values together in a function.
What is the correct way of doing this without returning NaN or undefined?
I've been trying to do by setting var values onkeyup or onclick as 'document.getelementbyid' only it never returns anything...
Some sample code would be,
HTML
<input type="radio" id="ServiceLevel" value="0.84" name="ServiceLevel"onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.67" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.56" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.28" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.14" name="ServiceLevel" onclick="getValue()"/>
and JS
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed(2));
}
You need to get the values in the javascript. Here is how you should do
Create a file index.htm
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>
script.js
function Calculate()
{
var v1 = document.getElementById ("a1").value;
var v2 = document.getElementById ("a2").value;
var v3 = document.getElementById ("a3").value;
var total = GetNumeric (v1) + GetNumeric(v2) + GetNumeric(v3);
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
first thing is
var ServiceLevel = document.getElementById(ServiceLevel).value;
// ServiceLevel = null
this should be in function else while opening this web page getElementById will give null.
2
. your input radio button has same name & ID if this is the case which value should be taken OR they are Individual OR Group
I tried this check:
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));
}

Categories