Selected Check box value display in URL with parameter using Php Javascript - javascript

I need to get selected check box value in browser url with parameter name.
My HTML code:
<div style="width:200px; float:left">
Price
<div>
<input type="checkbox" name="price" value="0-1000" class="filters" />0-1000<br />
<input type="checkbox" name="price" value="1000-2000" class="filters" />1000-2000<br />
<input type="checkbox" name="price" value="3000-4000" class="filters" />2000-3000<br />
</div>
Colors
<div>
<input type="checkbox" name="colors" value="Red" class="filters" />RED<br />
<input type="checkbox" name="colors" value="Green" class="filters" />GREEN<br />
<input type="checkbox" name="colors" value="Blue" class="filters" />BLUE<br />
</div>
</div>
My Javascript Code
<script type="text/javascript">
$('.filters').on('change',function(){
var price = new Array();
$('input[name=price]:checked').each(function(){
price.push($(this).val());
});
var colors = new Array();
$('input[name=colors]:checked').each(function(){
colors.push($(this).val());
});
location.href = 'http://localhost/test/javascript.php?price='+price;
});
</script>
I need Browser Url like below, after selecting two prices and one color
http://localhost/test/javascript.php?prices=0-1000,1000-2000&colors=Red

You are looking for .join()
The join() method joins the elements of an array into a string, and
returns the string.
The elements will be separated by a specified separator. The default
separator is comma (,).
location.href = 'http://localhost/test/javascript.php?price=' + price.join(',') + '&colors=' + colors.join(',');
Even though the comma seems to be the default separator , I would add it anyway just to be sure.
var url = 'http://localhost/test/javascript.php?';
if(price.length) {
url += '&price=' + price.join(',');
}
if(colors.length){
url += '&colors=' + colors.join(',');
}
location.href = url; // or url.replace('?&','?');

Related

Get an object from a DomElement Node without frameworks

I have an element in my page:
<form>
<div data-id="x">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
<div data-id="y">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
...other 100 inputs...
</form>
I'm looking for a javascript script like that:
var theElement = document.querySelector('[data-id="x"]');
var myObject = theElement.toObject();
And the object must looks like
{"field1":"Foo","field2":5}
I can't use the FormData strategy because I need a very small set of data from a very big form, but it is like a "partial FormData".
I'm asking if exists a standard method to convert the content of an HTMLElement in an object like for the FormData.
PS: i can use also the data-attribute if necessary
Actually there is no standard quicky method to do this task.
The solution is iterate over inputs and selects:
<script>
let myObj = {};
let element = document.querySelector('[data-id="x"]');
element.querySelectorAll('input').forEach(el=> {
// check the type
// the property is : el.name
// the value must be : el.value for text/number/email...
// the value for the type="checkbox" is according to checked attribute
});
element.querySelectorAll('select').forEach(sel=> {
// if multiple choise => create an array of selected options
// if single => check the selected option's value
});
</script>
This is the code i've used (simplified)

How to get multiple checkboxes values using id

I have a list of check boxes with different values.
<input type="checkbox" value="55" id="myId">
<input type="checkbox" value="65" id="myId">
<input type="checkbox" value="75" id="myId">
<input type="checkbox" value="85" id="myId">
<input type="checkbox" value="95" id="myId">
When I'm getting those values using js that will take only value=55 only. It is due to the same id="myId"
var x = "";
$("input[type='checkbox']").change(fucntion(){
if(this.checked){
x = x+","+x;
}
});
When run that will load only 55 values like-: 55,55,55,55
Attribute id should be unique. You can use an array instead of string variable. Then simply add or remove item based on the check box status:
var x = [];
$("input[type='checkbox']").change(function(){
if(this.checked){
x.push(this.value);
}
else {
var index = x.indexOf(this.value);
x.splice(index, 1);
}
console.log(x.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" id="">55
<input type="checkbox" value="65" id="">65
<input type="checkbox" value="75" id="">75
<input type="checkbox" value="85" id="">85
<input type="checkbox" value="95" id="">95
First of all don't use multiple same ids on your page, id should be unique on entire page, try data attributes instead
$("input[type='checkbox']").change(function(){
var x = "";
$("[data-id=myId]").each(function(){
if(this.checked){
x = x + $(this).val() + ",";
}
});
console.log(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" data-id="myId">
<input type="checkbox" value="65" data-id="myId">
<input type="checkbox" value="75" data-id="myId">
<input type="checkbox" value="85" data-id="myId">
<input type="checkbox" value="95" data-id="myId">
If selection order isn't important can map() the checked values to new array every change
Your string concatenation approach doesn't take into account unchecking a previously checked input
$(':checkbox').change(function(){
var vals = $(':checkbox:checked').map(function(){
return this.value
}).get()
console.log(vals.join())
})
// insert values as text for demo
.wrap(function(){
return $('<label>',{text:this.value})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" >
<input type="checkbox" value="65" >
<input type="checkbox" value="75">
<input type="checkbox" value="85" >
<input type="checkbox" value="95" >
Note that ID's must be unique in a page

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>

Radio buttons selected go to URL

I am trying to use the value of the selected radio button to go to a specific URL. Currently the Javascript I am using to do so is choosing the first "id" of the inputs and not using the value of what is actually selected.
HTML
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
Javascript
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + document.getElementById('ns_license').value;
}
</script>
You have multiple ID's that are the same, which is bad! getElementById expects one result, and it gets one by taking the first element which has that ID (ignoring your other 2, as it should). Use the class attribute on similar elements.
<input type="radio" name="ns_license" class="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" class="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" class="ns_license" value="1026" />NeuroSolutions Student
And to get the checked element
var checkedElem = document.querySelector(".ns_license:checked");
And if querySelector is out of the question:
var elems = document.getElementsByClassName("ns_license"),
checkedIndex = 0;
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked)
checkedIndex = i;
}
Your current checked element would be at elems[checkedIndex]
to change a a specific attribute of an element, you can use the
setAttribute()
function of javascript. that should make it work.
While querySelector will work for modern browsers it does not work for IE <=7
If you want you can traverse through the radios by name, then check if the value is checked. If it is then return that value. That is the use of the getRadioValue() function:
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + getRadioValue('ns_license');
}
function getRadioValue(name){
var rads = document.getElementsByName('ns_license');
for(var x=0; x<rads.length;x++){
if(rads[x].checked){
return rads[x].value;
}
}
}
</script>

javascript (math) adding up an array

I have two javascript text boxes.
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
How can I use javascript to alert the total price of the items in the text box?
Would something like this work?
var price = document.getElementById("test");
alert(price)
This will take all input elements into account (useful if you have many). Filter them by type and get their values in loop:
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++){
if (inputs[i].type = "text"){
total += parseInt(inputs[i].value, 10);
}
}
alert(total);
<input id="test1" type="text" name="test" value="300" />
<input id="test2" type="text" name="test" value="500" />
JS:
var price = parseInt(document.getElementById("test1").value, 10) + parseInt(document.getElementById("test2").value, 10);
<input id="price1" type="text" name="test" value="300" />
<input id="price2" type="text" name="test" value="500" />
This will work:
var price = document.getElementById("price1").value+document.getElementById("price2").value;
alert(price)
Note Do not have other tags with id="price1" or id="price2"
What you have written will not work, for several reasons. Firstly, as the name suggests, getElementById gets an element based on the value of the id attribute. You haven't given your input elements an id attribute, so that's not going to work.
Secondly, document.getElementById('someId') returns an element, but you want the value. You can use the value property to get it:
var price1 = parseInt(document.getElementById("test1").value, 10);
var price2 = parseInt(document.getElementById("test2").value, 10);
alert(price1 + price2);
This will work with the following HTML:
<input type="text" name="test" id="test1" value="300" />
<input type="text" name="test" id="test2" value="500" />
Note the use of parseInt. The value property returns a String, so we use parseInt to attempt to parse that into a Number. If you don't use it, price1 + price2 will simply concatenate the strings.

Categories