Updating URL with parameters from checkbox (without a hash) - javascript

I am using the following code snippet to pass parameters to URL so the specific search can be accessed via the generated link.
For example, if Potato is selected, then the URL changes to example.com#potato
However, instead of appending the URL with a hash, I want to append ?filter=
So if Potato is selected, I want the URL to change to example.com?filter=potato
How can I achieve this?
$(function() {
$(".vegetables, .seasoning").on("change", function() {
var hash = $(".vegetables:checked, .seasoning:checked").map(function() {
return this.value;
}).toArray();
hash = hash.join(",");
location.hash = hash;
});
if (location.hash !== "") {
var hash = location.hash.substr(1).split(",");
hash.forEach(function(value) {
$("input[value=" + value + "]").prop("checked", true);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h3>Filter recipes:</h3>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" class="vegetables" value="potato"> Potato</label><br>
<label><input type="checkbox" class="vegetables" value="onion"> Onion</label><br>
<label><input type="checkbox" class="vegetables" value="tomato"> Tomato</label><br>
</div>
<div>
<p>Select seasoning</p>
<label><input type="checkbox" class="seasoning" value="salt"> Salt</label><br>
<label><input type="checkbox" class="seasoning" value="pepper"> Pepper</label><br>
<label><input type="checkbox" class="seasoning" value="chilli"> Chilli Flakes</label><br>
</div>

You can use pushState() to update the current URL without reloading the page:
$(".vegetables, .seasoning").on("change", function() {
var values = $(".vegetables:checked, .seasoning:checked").map((i, el) => el.value).get();
window.history.pushState({}, '', `?filter=${values.join(',')}`);
});

Related

Dynamically loop through checkboxes and get their value and isChecked

I am dynamically printing out checkboxes depending on list from database, called in the code 'coachProperties'. Each coachProperty will get their own checkbox appended with the text which is unique.
I want to add this to another object 'properties'. Something like 'properties{text1 : "false, text2 : "true"} to then later on take it to server-side to do some filtering. I dont want any sumbit button since i want it to dynimcally update which i have js code for. All values in 'properties' will start with "false" which should update when checkbox is clicked. The problem is, sometimes when I uncheck a box it still displays as true and vice versa.
<div data-id="coachPropertiesCheckbox">
<% coachProperties.get('coachProperties').forEach(function (coachProperty) { %>
<div class="checkboxes">
<label>
<input type="checkbox" data-id="test" value="<%= coachProperty.text %>"> <%= coachProperty.text %>
</label>
</label>
</div>
<% }); %>
</div>
Js code:
function setProp(obj,prop,value){
obj[prop] = value;
};
var properties = {};
coachProperties.get('coachProperties').forEach(function (coachProperty) {
properties[coachProperty.text] = "false";
});
view.$el.find('[data-id="coachPropertiesCheckbox"] div.checkboxes input').change(function () {
var isCheckboxedChecked = view.$el.find('[data-id="test"]').is(':checked');
var valueCheckbox = $(this).attr("value");
setProp(properties, valueCheckbox, isCheckboxedChecked );
$.each( properties, function( key, value ) {
console.log( key + ": " + value );
});
});
Use value property to hold data that you would like to associate with the checkbox and do not use it to toggle true and false. Whether checkbox is checked or not, you can know from the checked property.
A piece of advice, most probably, you'll NOT want to use checkbox label same as value because values are for internal purpose, for any data manipulation, and labels have sole purpose of display in the UI.
Please try the following solution direction:
$('.checkboxes input').on('change', (event) => {
const checked = $(event.target).prop('checked')
const value = $(event.target).prop('value')
console.log(checked, ':', value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="checkbox1-id" value="checkbox-1" /><label for="checkbox1-id">Checkbox 1</label>
<input type="checkbox" id="checkbox2-id" value="checkbox-2" /><label for="checkbox2-id">Checkbox 2</label>
<input type="checkbox" id="checkbox3-id" value="checkbox-3" /><label for="checkbox3-id">Checkbox 3</label>
</div>
view.$el.find('div.checkboxes input').change(function (event) {
var id = $(event.target).attr('data-id');
if ($(event.target).prop('checked')) {
resultSetParameters.get('filter').coachProperties.push(id);
resultSetParameters.trigger('change');
} else {
var index = resultSetParameters.get('filter').coachProperties.indexOf(id);
if (index > -1) {
resultSetParameters.get('filter').coachProperties.splice(index, 1);
resultSetParameters.trigger('change');
}
}
});

Dynamic number of inputs

I have problem with dynamic number of radio input in array like that
Color:<br>
<label><input type="radio" name="params[54]" value="21">Blue</label>
<label><input type="radio" name="params[54]" value="38">Yellow</label>
Size:<br>
<label><input type="radio" name="params[12]" value="32">S</label>
<label><input type="radio" name="params[12]" value="44">M</label>
<label><input type="radio" name="params[12]" value="58">L</label>
It could not be only Color and Size and it shoud have more than two or three inputs.
I use VueJS Component.
export default {
data () {
return {
params: {}
}
},
methods:{
update: function(){
// here I want use params
}
}
}
I need watch change input and get params object witch one are selected like:
{
54: 21,
12: 44
}
In my old jQuery code I do this like that
$("input[type=radio]").on("change", function(){
var selected = {};
$("input:checked").each(function(a, b){
selected[$(b).data("param-id")] = $(b).data("value-id");
});
});
But in this I seriously don't know how can I do this in Vue. Any ideas?
EDIT:
I sove it by passing list of params
var params = JSON.parse(this.$attrs.params);
for(var key in params){
this.$set(this.params, key, 0);
this.$watch("params."+key, function(){
this.update();
});
}
And adding v-model to input
<label>
<input
:checked="params[54] == 21"
v-model="params[54]"
type="radio"
name="params[54]"
v-bind:value="21"
>
Blue
</label>
Now I can use this.attributes to get object of selected params.

selected checkbox even after reload the page

I need checkbox selected after page reload I am trying this code.
Here my check box
<tr>
<td class="label" style="text-align:right">Company:</td>
<td class="bodyBlack">
<%=c B.getCompanyName() %>
</td>
<td>
<input type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px">> Show all paid and unpaid transactions
<br>
</td>
</tr>
//here java script code
<script type="text/javascript">
function checkBox12() {
var jagdi = document.getElementById("check").value;
if (jagdi != "") {
document.getElementById("check").checked = true;
}
console.log("jagdi is " + jagdi);
//here my url
window.location.replace("/reports/buyers/statementAccount.jsp?all=" + jagdi);
return $('#check').is(':checked');
}
</script>
Add attribute checked=checked in your html input tag:
<input checked="checked" type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px"/>
Why don't you use only jQuery ?
function checkBox12()
{
var jagdi = false;
if($("#check").length != 0) // use this if you wanted to verify if the element #check is present
jagdi = $("#check").prop("checked");
//here my url
window.location.replace("/reports/buyers/statementAccount.jsp?all="+jagdi);
}
For answer your question, you can check your checkbox when the document is ready
$(document).ready(function() {
$("check").prop("checked", true");
});
But the better way is to add checked="checked" in your HTML. The checkbox will be checked by default. /!\ input need "/" in close tag
<input type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px" checked="checked" />
It looks like you are using some other base language. I use php , and it overs POST, GET and SESSION to store values globally and for time you need.
Better find a equivalent function in your language. worth it in long term and on project expansion.
You can store state of checkbox on cookie and repopulate it after page reload.
also there is an example in here HERE!
$(":checkbox").on("change", function(){
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
});
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();

How to persist checkbox checked state after page reload?

I am unable to persist checkbox checked after page is refreshed.
You need to use cookies for this... As soon as user clicks on check box, store its state into a cookie and just fetch the cookie value on page load to prepoulate the checkboxes as they were in previous selection.
HTML
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<button>Check all</button>
Fetching checkboxes value and making a cookie out of them
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
Function to read cookies to prepopulate on load
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
Working Fiddle
You have to do this on server side. Either with PHP, ASP.NET or whatever you use.
This is the only way.
Or, if your website is client-side only, then you would have to implement it without any page refreshing.
Here how I do it:
<html>
<input type="checkbox" <?php echo file_get_contents(".cktest"); ?> onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with php<br/>
<!-- with ajax read the checked attribut from file -->
<input id="withajax" type="checkbox" onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with ajax<br/>
<script>
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
function show_write(text) {
//alert(text);
}
//
getFileFromServer(".cktest", function(x) { document.getElementById("withajax").checked=x;} );
</script>
</html>
and the file write_ckfile.php:
<?php
$strtarget=$_GET['target'];
$status=$_GET['value']=="true"?"checked":"";
file_put_contents($strtarget, $status );
?>
I hope this helps.
MiKL~

take input value from a selected checkbox and show it in url box

I have some check box to get Brand name and size, i want to display value for selected check box in url box like
www.xyz.com?brands=P,Q,R&Size=2,3
I've this code that shows,
www.xyz.com?brands=P&brands=Q&brands=R&Size=2&Size=3
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$('input[type="checkbox"]').on('change', function(e) {
var data = [],
loc = $('<a>', {
href: window.location
})[0];
$('input[type="checkbox"]').each(function() {
if (this.checked) {
data.push(this.name + '=' + this.value);
}
});
data = data.join('&');
$.post('/ajax-post-url/', data);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + data);
}
});
</script>
HTML
<div class="pane">
<div class="ele">
<input type="checkbox" value="X" name="Brand">
<label>Brand 1</label>
<input type="checkbox" value="Y" name="Brand">
<label>Brand 2</label>
<input type="checkbox" value="Z" name="Brand">
<label>Brand 3</label>
<input type="checkbox" value="1" name="Size">
<label>Size 1</label>
<input type="checkbox" value="2" name="Size">
<label>Size 2</label>
<input type="checkbox" value="3" name="Size">
<label>Size 3</label>
</div>
</div>
You can change your script this way:
$('input[type="checkbox"]').on('change', function(e) {
var data = {}; // 1
var dataStrings = []; // 2
$('input[type="checkbox"]').each(function() { // 3
if (this.checked) {
if (data[this.name] === undefined) data[this.name] = []; // 4
data[this.name].push(this.value); // 5
}
});
$.each(data, function(key, value) // 6
{
dataStrings.push(key + "=" + value.join(','));
});
var result = dataStrings.join('&'); // 7
alert(result);
$.post('/ajax-post-url/', data);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + data);
}
});
Here is a JSFiddle: http://jsfiddle.net/8ct2mbpa/
This is how it works:
data is an object which consists of ARRAYS of selected values
dataStrings is an array which consists of key-value pairs
First, we iterate through all selected checkboxes
If such array is not yet presented, we create it. For example, data['Brand'] is an empty array now
We add a selected value. data['Brand'] is now filled with values ['X', 'Y', 'Z']
Combine values in key-value pairs. It now becomes Brand=X,Y,Z
Join all key-value pairs using "&" sign
I think you're looking for this:
How do I pass a URL with multiple parameters into a URL?
That said, I think this question could be marked as a double.

Categories

Resources