I wanna implement this using jquery instead of inline but Its not working, inline works fine. The other reason I wanna use jquery is if user selects more than one checkbox, the url should be appended with whatever is already there + OR '2nd CheckBox Value' like this:
"http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office OR Hospital"
The space infront and following OR is fine..
How can I achieve this? Can someone help me out?
Offices<input name="LocType" type="checkbox"
value="Office" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office'; return true;">
Hospitals<input name="LocType" type="checkbox"
value="Hospital" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Hospital'; return true;">
Facilities<input name="LocType" type="checkbox"
value="Facility" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Facility'; return true;">
Bind to the change event on the checkboxes. When clicked read the current checkbox value and then all other relative checkboxes. Append your base url with your custom query string and go crazy. :)
This isn't tested but hopefully it's a good starting point.
var baseUrl = 'http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
You can try this.
HTML
<input name="LocType" type="checkbox" value="Office" />
<input name="LocType" type="checkbox" value="Hospital" />
<input name="LocType" type="checkbox" value="Facility" />
JS
Assuming you have a button or something on click of which you want to create a url with all the checked LocType checkbox values appended to the url seperated by OR
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('button').click(function(){
//This will get the array containing values of checked LocType checkboxes
var checkedLocTypeValues = $('input[name=LocType]:checked').map(function(){
return this.value;
});
//Use Array.join() method to join the array elements by " OR "
url = url + "&k=" + checkedLocTypeValues.join(" OR ");
//Now you can use url variable which has all the checked LocType checkboxes value
}
jQuery map() reference - http://api.jquery.com/jQuery.map/
Related
I'm trying to create a simple HTML page that presents a user with several options via checkboxes. I need to generate a string, stored in a variable that I can use on the page when a button is clicked, which will vary based on which boxes are checked.
The string will be a URL ("http://example.com/index.htm&term=") and will need to have additional text appended to it for each checkbox that is checked.
For example, if only a single box, say box1, is checked the string "box1" should be appended to the URL variable to look like "http://example.com/index.htm&term=box1"
If, however more than one box is checked, say box2 and box3 are checked, then the string "box2%20OR%20box3" should be appended to the URL string.
I'm pretty sure this can be done with JavaScript but I have no experience with it and would appreciate some guidance/examples.
Instead of storing it in a variable, I would recommend calling a function that builds the link when the button is pressed. If you really wanted to put it in a variable though, you would set up an event listener for the change event for each checkbox, and call the function to update the variable each time one of the checkboxes is checked or unchecked.
function checkboxUrl(checkboxes) {
const
url = `http://example.com/index.html`,
checkedArray = [];
for (let checkbox of checkboxes) {
if (checkbox.checked) checkedArray.push(checkbox);
};
const checkboxString = checkedArray.map(checkbox => checkbox.value).join(`%20OR%20`);
return url + (checkboxString ? `?term=` + checkboxString : ``);
}
let checkboxes = document.querySelectorAll(`input[type='checkbox']`);
label {
display: block;
}
<label><input type='checkbox' value='box1'>box1</label>
<label><input type='checkbox' value='box2'>box2</label>
<label><input type='checkbox' value='box3'>box3</label>
<button onclick='console.log(checkboxUrl(checkboxes))'>Get URL</button>
If you use Jquery you can do something like this:
<input type="checkbox" id="box1">
<input type="checkbox" id="box2">
<button type="button" id="myButton">Submit</button>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
var url = 'www.myurl.com/index.html&term=';
var checkboxList = [];
var params = '';
$(':checkbox:checked').each(function(){
checkboxList.push($(this).attr('id'));
});
params = checkboxList.join('%'); //will output "box1%box2"
url += params //www.myurl.com/index.html&term=box1%box2
window.location.href = url;
});
});
</script>
Ok so here is the end goal.
In the end I will be working with multiple checkboxes that are going to be filtering results on a page. When a certain checkbox is checked it will append the value to the url.
Then I need to sort of do the opposite thing. If a user enters that specific URL it would change the default of that checkbox to checked.
I have the code working however I am not able to do it with specific checkboxes, it just continues to pull from the first value it finds. I know there is a better way than creating different click functions for every checkbox and running different statements for each, I just can't seem to figure that part out.
Here is what I have:
<input type="checkbox" id="business" class="myCheckbox" value="business" name="Industry"/> Business Communcations<br>
<input type="checkbox" id="construction" class="myCheckbox" value="construction" name="Industry"/> Construction<br>
<input type="checkbox" id="education" class="myCheckbox" value="education" name="Industry"/> Education<br>
<input type="checkbox" id="energy" class="myCheckbox" value="energy" name="Industry"/> Energy
<script type="text/javascript">
var url = location.search;
var check = $(".myCheckbox");
var checkValue = check.attr('value');
var attr = $('.myCheckbox').attr('checked');
// When checked, append value to URL
$(".myCheckbox").click(function() {
this.setAttribute("checked", "checked");
if(typeof attr !== undefined && attr !== false){
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + checkValue;
window.history.pushState({path:newurl},'',newurl);
}
});
// Check if url = value for default checkmarks
$(document).ready(function() {
if (window.location.search == "?" + checkValue) {
business.setAttribute("checked", "checked");
}
});
</script>
Thanks for the help!
I'm trying to create a 2checkout buy now button. In order to get the correct products into the cart, you need to pass product ID's into the URL. I'm trying to build the URL based on how the user checks and unchecks checkboxes.
For example:
When the user checks a checkbox, a URL parameter is added to the base URL using &product_id=
$("#buynow").attr('href', function(){
var baseURL = this.href;
var newURL = baseURL + '&product_id=' + productID;
return newURL;
})
The user unchecks the checkbox, therefore, removing the product ID from the URL:
$("#buynow").attr('href', function(){
var oldURL = this.href;
var newURL = oldURL.substr(oldURL.lastIndexOf('&'));
return url.replace( new RegExp(oldURL), '' );
})
The problem I'm having is that I have multiple checkboxes that add and remove to the URL.
Typical scenerio:
User checks checkbox A product_id=1, and then checks checkbox B product_id1=2.
http://baseurl.com/sid=12345&product_id=1&product_id1=2
User decided to uncheck checkbox A. The code removes the lastIndexOf based on '&' which then removes checkbox B product ID.
How can I write the code such that it removes not just the last parameter added to the URL, however, it knows which product to remove based on the ID of the product.
Hope this makes sense.
Here is a simple example to update href based on checkbox's name and value.
$(".url_p").change(function() {
var href = "http://baseurl.com/";
$(".url_p").each(function(i) {
if (!$(this).is(":checked")) return;
href += (href.indexOf("?")==-1 ? "?" : "&") + this.name + "=" + encodeURIComponent($(this).val());
});
console.log(href);
$("#buynow").attr("href", href);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' class='url_p' name='product_id' value='100'>Product id
<br/>
<input type='checkbox' class='url_p' name='price' value='80'>Price
<br/>
<input type='checkbox' class='url_p' name='amount' value='1'>Amount
<br/>
<a id='buynow' href='#'>Buy Now</a>
I am trying to collect multiple pieces of data from a checkbox, but I am unsure of how to do this. Right now I have:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" style="display:inline-block;">
Which allows me to collect an id (contained in {{$friend}}) that I need. But I also need the name associated with this id. Is there a way to collect multiple values from a single checkbox? I would need this because I am collecting the data and moving to another form without changing the view. This would be used for javascript which would print out stuff in the view as it is checked (i.e. the id and name).
Here is the javascript:
<script>
$(document).ready(function(){
var callbacks_list = $('.callbacks ul');
$('.facebook-friends-larger input').on('ifChecked', function(event){
callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');
});
$('.facebook-friends-larger input').on('ifUnchecked', function(event) {
callbacks_list.find('span#'+ this.id).closest('li').remove();
console.log(this.id);
});
});
</script>
Any ideas? Thank you for your help.
Try this this will be helpyou..
$("input[type=checkbox]").change(function(){
alert($(this).val()); //get a val
alert($(this).attr('name')); //get a value of name attribute
});
Fiddle here
If you have the access to the username before the page is loaded (and is therefore able to inject it into the DOM without making ajax queries after pageload or user action), you can store them in HTML5 data- attributes, for example, data-name in the following format:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" data-name="{{name}}" style="display:inline-block;">
You can access the name by simply calling the .data() method in jQuery, i.e. $('input').data('name').
Use:
var name = $("#checkbox-id").attr("name"); // Use whatever method you have to target the checkbox
and so on to get the other values
Try this
HTML
<input tabindex="1" type="checkbox" name="friend[]" id="123" value="{{$friend}}" style="display:inline-block;">test
JS
$(document).ready(function(){
$("#123").change(function(){
$(this).val(); //get a val
console.log($(this).attr('name')); //get a value of name attribute
});
});
FIDDLE
I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />