get value from url than select the checkbox using javascript - javascript

When I click on the checkbox dynamic url create. If I refresh the page than checkbox show selected if brand name have some value my javascript code working fine.
Shop?brand=Emporio,Primigi%2088&category=&gender=&start=2000&end=4000
The problem is if brand name contain space like primigi 88, Lee Cooper than it select all the checkbox. I want to select the checkbox only that is in url.
$(function() {
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL =
decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var brand = getUrlParameter('brand');
if (brand) {
var brand_array = brand.split(",");
for (var i = 0; i < brand_array.length; i++) {
$('input[type=checkbox][value=' + brand_array[i] +
']').attr('checked', true); // this will working fine if categories name not contain any space
}
}
var category = getUrlParameter('category');
if (category) {
var category_array = category.split(",");
for (var i = 0; i < category_array.length; i++) {
$('input[type=checkbox][value=' + category_array[i] +
']').attr('checked', true);
}
}
var gender = getUrlParameter('gender');
if (gender) {
var gender_array = gender.split(",");
for (var j = 0; j < gender_array.length; j++) {
$('input[type=checkbox][value=' + gender_array[j] +
']').attr('checked', true);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group">
<h3>Brands</h3>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="North East">North East</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Emporio">Emporio</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Lee Cooper">Lee Cooper</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Primigi 88">Primigi 88</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Us polo assn">Us polo assn</a>
</div>

The issue is because you need to wrap the value in the attribute selector in quotes so that the spaces are also included, eg:
$('input[type="checkbox"][value="' + gender_array[j] + '"]')
That being said there's a few things you can do to improve your logic. Firstly, use prop() instead of attr() where possible. Secondly, you don't need the function name when declaring a function as a variable.
Lastly, you can also DRY up the logic by removing the repeated block that checks the checkboxes by building one large array of all the filters and looping through that. Try this:
$(function() {
var getUrlParameter = function(sParam) {
// param retrieval logic...
};
var brands = (getUrlParameter('brand') || '').split(',');
var categories = (getUrlParameter('category') || '').split(',');
var genders = (getUrlParameter('gender') || '').split(',');
var filters = brands.concat(categories).concat(genders);
filters.forEach(function(filter) {
$(`input[type="checkbox"][value="${filter}"]`).prop('checked', true);
});
});

Related

Appending and removing URL parameters based on checkboxes

I have some filters that are being displayed as checkboxes on my website. Each time someone checks or unchecks one of these inputs I either want to add or remove the filter to/from the URL. I have this mostly working, but the problem comes when removing the last filter in the list.
Here's an example:
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
$(function () {
var colors = getUrlParameter('colors');
var currentUrl = location.href;
$('input[type="checkbox"]').change(function () {
var inputVal = $(this).val();
if (this.checked) {
// Add filter to URL params
colors = getUrlParameter('colors');
if (!colors) {
// No filters exist yet
currentUrl += '?colors=' + inputVal;
} else {
// At least one filter exists
currentUrl += ',' + inputVal;
}
console.log(currentUrl);
window.history.pushState("object or string", "Title", currentUrl);
} else {
// Remove filter from URL params
currentUrl = currentUrl.replace(inputVal + ',', '');
console.log(currentUrl);
window.history.pushState("object or string", "Title", currentUrl);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filters">
<label><input type="checkbox" value="blue" />Blue</label>
<label><input type="checkbox" value="red" />Red</label>
<label><input type="checkbox" value="green" />Green</label>
</div>
This works if the color is first(if there or other filters) or in the middle of the list of filters, since it matches my replace(), wondering how I can do this dynamically so that it will remove both the color and the comma if necessary or remove the colors= altogether if none are checked.
For example, if all 3 colors are checked the url would look like this:
http://example.net?colors=blue,red,green
If you then remove blue it should look like this:
http://example.net?colors=red,green
If you then remove green it would look like this:
http://example.net?colors=red
And finally, removing red would look like this:
http://example.net
You'll want to split your colors into an array and then merge it back again at the end.
$(function () {
var colors = getUrlParameter('colors');
var currentUrl = location.href;
$('input[type="checkbox"]').change(function () {
var inputVal = $(this).val();
var colorsQuery = getUrlParameter('colors') || "";
//Split into an array after each `,`
colors = colors.split(",");
if (this.checked) {
//Add to our current colors
colors.push(inputVal);
} else {
// Remove from our current colors
const index = colors.indexOf(inputValue);
colors.splice(index, 1);
}
colorString = "";
if(colors.length){
//Merge back into a string with a `,`
colorString = "?colors=" + colors.join(",")
}
window.history.pushState("object or string", "Title", currentUrl + colorString);
});
});
It's much easier to work with arrays in this instance so we just split and join to convert to and from an string to array.
For adding its easy we can just push onto our array
To remove a color we find out where it is in our colors array. Then using splice remove it from our array.
I'd seperate adding and removing objects, and the logic to get your querystring.
You'll see here two basic events:
Update an object based on the current checkbox (Binding directly to the state is even better!)
Generating the string based off of current values.
var colors = {
'red': false,
'blue': false,
'green': false
};
update = function(color) {
colors[color] = !colors[color];
}
getParams = function() {
var setQuery = false;
var expr = [];
for (var color in colors) {
if (colors[color]) {
expr.push(color);
setQuery = true;
}
}
if (setQuery) {
console.log("www.example.com" + "?colors=" + expr.join(","));
} else {
console.log("www.example.com");
}
}
<input type="checkbox" onchange="update('red')" /> Red
<input type="checkbox" onchange="update('blue')" /> Blue
<input type="checkbox" onchange="update('green')" /> green
<button type="button" onclick="getParams()">Get params</button>

How to add object which checked in array?

I have checkboxes in the application, When I click check-box , The object which I checked, is added in array. But When I click one more time checkbox (unchecked), The object is not removed in array.
How can I fix it ?
HTML Source:
<ion-list ng-repeat="option in question.SurveyOptions ">
<li class="item item-checkbox checkbox-royal ">
<label class="checkbox">
<input type="checkbox" ng-checked="MyAnswers.indexOf(option)!=-1" ng-click="toggleCheckAnswer({OptionId:option.Id,QuestionId:question.Id})">
</label>
<div class="item item-text-wrap">
{{option.OptionsName}}
</div>
</li>
</ion-list>
Controller:
$scope.MyAnswers = [];
$scope.toggleCheckAnswer = function(Answer) {
if ($scope.MyAnswers.indexOf(Answer) === -1) {
$scope.MyAnswers.push(Answer);
} else {
$scope.MyAnswers.splice($scope.MyAnswers.indexOf(Answer), 1);
}
};
In the function Answer include only OptionId and QuestionId.
How can I find index of {OptionId:1,QuestionId:1}?
Try like this
var index = $scope.MyAnswers.map(function(x) {
return x.OptionId + "#" + x.QuestionId;
}).indexOf(Answer.OptionId + "#" + Answer.QuestionId);
console.log(index);
You can't use indexOf to find objets in array you need to iterate over array:
$scope.toggleCheckAnswer=function(Answer) {
var index = -1;
for (var i=0; i<$scope.MyAnswers.length; ++i) {
var answer = $scope.MyAnswers[i];
if ($scope.MyAnswers[i].OptionId == Answer.OptionId &&
$scope.MyAnswers[i].QuestionId == Answer.QuestionId) {
index = 1;
break;
}
}
if (index === -1) {
$scope.MyAnswers.push(Answer);
} else {
$scope.MyAnswers.splice(index, 1);
}
};

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Adding values of variable form fields

I have fields of type='number' in my form. These are dynamically generated by a database.
<input name="each[29]" id="form_29" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
<input name="each[30]" id="form_30" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
<input name="each[31]" id="form_31" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
The attribute name="each[xx]" is an ID of a category in the database. Here is the submit button:
<input type="submit" value="Enregistrer" onClick="return calculAuto('form_29,form_30,form_31')">
JavaScript
function calculAuto(v) {
var mystr = v;
var myarr = mystr.split(",");
var cat = '';
for (i = 0; i < myarr.length; i++) {
if ($('#' + myarr[i]).val() !== '') {
cat += $('#' + myarr[i]).val();
}
}
}
I want to calculate the sum of all the fields passed in the argument of the function.
you are doing:
var cat = ''; //string
so with cat += $('#' + myarr[i]).val();
its appending the values, do:
function calculAuto(v) {
var mystr = v;
var myarr = mystr.split(",");
var cat = 0;
for (i = 0; i < myarr.length; i++) {
if ($('#' + myarr[i]).val() !== '') {
cat += $('#' + myarr[i]).val();
}
}
console.log(cat);
return false;
}

Radio Button list selected items value in javascript

I am using following code to get the selected elements value in radio button list.
function SelectRadioButton()
{
var radiobutton = document.getElementsByName('<%=RadioButtonList1.ClientID %>');
alert(radiobutton.length);
for(var x = 0; x < radiobutton.length; x++)
{
if(radiobutton[x].checked)
{
alert('selected is ' + radiobutton[x].id);
}
}
}
Following is the HTML markup
<table id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1" class="chk" onclick="javascript:SelectRadioButton(this, ctl00_ContentPlaceHolder1_idControl_RadioButtonList1)" border="0">
<tr>
<td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="1" checked="checked" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0">List</label></td><td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="2" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1">Assignment</label>
But I am getting length 0 in alert(radiobutton.length); statement.
Why is this happening. any thing that I am missing?
You can use jquery to do this.
alert($(".chk").find("input:checked").length); // chk is your css class name applied to Checkbox List element.
You can get specific element by using this
alert($(".chk").find("input:checked")[0]);
RadioButtonList1 will be converted to radio buttons with ids having RadioButtonList1, You can iterate through DOM and look for matched ids and put them in some array or directly perform what you want to them.
radiobutton = [];
for(i=0;i<document.forms[0].length;i++)
{
e=document.forms[0].elements[i];
if (e.id.indexOf("RadioButtonList1") != -1 )
{
radiobutton.push(e);
}
}
Here's how you do it with javascript only, if you don't want to use getElementById
Code | JSFiddle
function SelectRadioButton(){
var radiolist = getElementsByClass("table", "chk")[0],
radios = radiolist.getElementsByTagName("input");
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
alert('Selected radiobutton is ' + radios[i].id);
}
}
}
function getElementsByClass(tag, name){
var elements = document.getElementsByTagName(tag);
var ret = [];
for(var i = 0; i < elements.length; i++){
if(elements[i].className.indexOf(name) !== -1){
ret.push(elements[i]);
}
}
return ret;
}

Categories

Resources