I woult to use checkbox and javascript to filter search results.
Actually I use this code to alterate url and obtain results but I would to obtain results in this format: ?A=A1,A2&B=B1,B2&C=C1,C2 instead ?A=A1&A=A2&B=B1$B=B2&C=C1&C=C2
This is the code
<input type="checkbox" name="a" value="A1" /> A1 Value
<input type="checkbox" name="a" value="A2" /> A2 Value
<input type="checkbox" name="b" value="B1" /> B1 Value
<input type="checkbox" name="b" value="B2" /> B2 Value
<input type="checkbox" name="c" value="C1" /> C1 Value
<input type="checkbox" name="c" value="C2" /> C2 Value
<input type="button" value="Test" onclick="javascript:checkbox_test()">
<script type="text/javascript">
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked === true) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + '&c=' + input_obj[i].value;
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
// or you can send checkbox values
// window.location.href = 'my_page.php?' + url;
}
else {
alert('There is no checked checkbox');
}
}
</script>
Here you go:
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
var arr = [];
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked === true) {
// ... increase counter and concatenate checkbox value to the url string
if (arr.indexOf(input_obj[i].name) == -1) {
arr.push(input_obj[i].name);
url = url + '&' + input_obj[i].name + '=';
counter = 0;
}
if (counter > 0) {
url = url + ',';
}
url = url + input_obj[i].value;
counter++;
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
// or you can send checkbox values
// window.location.href = 'my_page.php?' + url;
}
else {
alert('There is no checked checkbox');
}
}
See DEMO
try this:
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = new Array(), // final url string
input_obj = document.getElementsByTagName('input');
ck = {};
for (i = 0; i < input_obj.length; i++) {
if (input_obj[i].type === 'checkbox' && input_obj[i].checked === true) {
if(ck[input_obj[i].name] == undefined) ck[input_obj[i].name] = new Array();
ck[input_obj[i].name].push(input_obj[i].value);
counter++;
}
}
for (k in ck) {
url.push(k + '=' + ck[k].join(','));
}
if (counter > 0) {
alert('?' + url.join('&'));
}
else {
alert('There is no checked checkbox');
}
}
You're better off using document.querySelectorAll() instead of looping through all this yourself. See this fiddle.
here's the relvant part:
var boxes = document.querySelectorAll("input[type='checkbox']:checked");
if (boxes.length > 0) {
//convert nodeList to Array and transform to name=value pairs
var querystring = Array.prototype.slice.call(boxes)
.map(function (box, index) {
alert(box);
return escape(box.name) + '=' + escape(box.value);
})
.join("&"); //turn into querystring
alert(querystring);
}
Related
I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values.
function validateForm() {
var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5"
var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5
var i;
for (i = 1; i <= lastCharRow; i++) {
var nameValidate[] = document.forms["packageForm"]["packageItemName"].value;
if(nameValidate[i].length<1){
alert('Please fill: '+nameValidate[i]);
return false;
}
}
}
How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code
var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value;
Like this
const validatePackageItems = () => {
const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName
const vals = nameValidate.map(function() { return this.value }).get(); // all values
const filled = vals.filter(val => val.trim() !== ""); // all values not empty
console.log("Filled", filled, "= ", filled.length, "filled of", vals.length)
return filled.length === vals.length
};
$("[name=packageForm]").on("submit",(e) => {
if (!validatePackageItems()) {
alert("not valid");
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="packageForm">
<input type="text" name="packageItemName1" value="one" /><br/>
<input type="text" name="packageItemName2" value="two" /><br/>
<input type="text" name="packageItemName3" value="" /><br/>
<input type="text" name="packageItemName4" value="four" /><br/>
<input type="submit">
</form>
You can use string interpolation to get the key dynamically:
for (let i = 1; i < 6; i++) {
const currentValue = document.forms.packageForm[`packageItemName${i}`]
console.log('current value:', currentValue)
}
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>
I have few radio buttons:
<input type="radio" value="####.###/resources/videos/7.mp4">
<input type="radio" value="####.###/resources/videos/8.mp4">
<input type="radio" value="####.###/resources/videos/9.mp4">
How can I make an array containing the selected values like following:
var videos = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"];
Onclick push the value of radio in array
var arr=[];
$('input').click(function(){
arr.push("."+$(this).val().split('####.###')[1])
console.log(arr);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="####.###/resources/videos/7.mp4">Video1
<input type="radio" value="####.###/resources/videos/8.mp4">Video2
<input type="radio" value="####.###/resources/videos/9.mp4">Video3
I would add a change event listener, that checks if the input got checked or unchecked and would add it or remove it from the list.
var originalVideoList = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"
];
var videos = document.querySelector("#videos");
var result = document.querySelector("#result");
var template = "<li><label for='{0}'>Video {1}</label><input id='{0}' type='checkbox' onchange='onChange()'/></li>";
var selectedArray = [];
// Set up html
videos.innerHTML = originalVideoList.map(function(video) {
return template.replace(/\{0\}/g, video).replace(/\{1\}/g, video.split("/").pop());
}).join("");
// triggered on input change
function onChange() {
selectedArray = toArray(document.querySelectorAll("li>input:checked")).map(function(item) {
return item.id.replace("####.###", ".");
});
result.innerHTML = selectedArray.map(function(video) {
return "<li>" + video + "</li>";
}).join("");
}
// Same as [...input]
function toArray(input) {
var result = [];
for (var index = 0; index < input.length; index++) result[index] = input[index];
return result;
}
<ul id="videos"></ul>
<ul id="result"></ul>
I want to display the form with user filled values inside the form to admin. I have displayed all type of values to the respective type of input/select/textarea tags (type: text,email, tel,number... etc) except input type=checkbox.
I am getting problem while fetching the values from array that contain values of group of checkboxes. My code is
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var value1 in value) {
console.log(value1);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value1 + "']").attr('checked', true); //cb
}
}
my array(named value) contain values like
[cricket, football, tennis]
would like to make the checkbox property checked that match the condition. but when i console the values fetched one by one it shows me output as
0
1
2
i am not getting what is it???
my html code
<table class="form-group">
<tbody id="tedit">
<tr>
<td>
<div class="checkbox">
<input id="dddddddd#1428735544884535#check_box1" class="form-control" name="14287355448849394#dddddddd[]" groupid="14287355448849394" grid-name="dddddddd" value="Check Box1" type="checkbox" /><label class="jedit"><span class="mouseover">Check Box1</span></label>
</div>
</td>
</tr>
<tr>
<td>
<div class="checkbox">
<input id="dddddddd#14287355448843282#check_box2" class="form-control" groupid="14287355448849394" grid-name="dddddddd" name="14287355448849394#dddddddd[]" value="Check Box2" type="checkbox" /> <label class="jedit"> <span class="mouseover">Check Box2</span></label>
</div>
</td>
</tr>
<tr>
<td>
<div class="checkbox">
<input id="dddddddd#14287355448853367#check_box3" class="form-control" groupid="14287355448849394" grid-name="dddddddd" name="14287355448849394#dddddddd[]" value="Check Box3" type="checkbox" /> <label class="jedit"> <span class="mouseover">Check Box3</span></label>
</div>
</td>
</tr>
</tbody>
</table>
my javascript code is
$.post('<?php echo BASE_URL . 'php/processing/formDashboard/formEntryShowOneByOne.php' ?>', {id: $('#formMetaDataId').val()}, function(data) {
console.log(data);
for (var i = 0, len = data.length; i < len; i++) {
for (var key in data[i]) {
$("input[type='text'][name='" + key + "']").val(data[i][key]); //input tags
$("input[type='text'][name='" + key + "']").prop('disabled', 'true'); //input tags
//........likewise for other type of elements.......///
//.....................for checkbox........................//
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var value1 in value) {
console.log(value1);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value1 + "']").attr('checked', true); //cb
}
}
}
}
});
this is simple. The 'cricket' string is retrievable like this:
value[value1]
value1 is just the iterator, in your example 0,1,2
This is your working code:
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var value1 in value) {
console.log(value[value1]);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value[value1] + "']").attr('checked', true); //cb
}
}
You should use forEach function
value.forEach(function(val)
{
console.log(val);
//do your thing here
});
That's just how the for ... in loop works for arrays:
var a = ['a','b','c'];
for (var i in a) {
alert(i); // alerts 0,1,2
alert(a[i]); // alerts a,b,c
}
Thus, you just need to index your array with the loop variable:
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var valueIndex in value) {
console.log(value[valueIndex]);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value[valueIndex] + "']").attr('checked', true); //cb
}
}
I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>