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>
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 am a very rudimentary user of JavaScript and jQuery.
I have a form that builds a simple search URL based on user input, and uses the GET method to send the user to a set of filtered search results on a site at another domain. There is a base URL, and the form inputs are appended to it, as in
http://www.othersite.com/search.asp?q=input1&id=input2
My problem is that the other site uses an item ID in the search URL that is different than the item name. The users are going to know the item name, but the item ID is just a sequential key value.
I want to have the user enter the item name (along with some other input terms), and have the corresponding key value appended to the URL when it is submitted.
I have all the pairs of item names and IDs in a JSON file that I can format as needed. There are about 15,000 pairs.
So for example, the item named abc123 has an ID of 54321.
I want the user to enter abc123 in a text field, and to have itemID=54321 appended to the base search URL.
I do not find any close examples I can borrow from.
Sorry if this is too long of an answer. The below method uses the datalist element along with an input list element that gets populated with an xhr request. Also, don't forget that Safari doesn't do datalists :(... User beware this hasn't been tested.
<form id='search-form' method='GET'>
<input list='search-data'
name='item-title'
id='search-input'
value=''
placeholder='Search Titles'>
<datalist id='search-data'>
</datalist>
<input type='submit' name='submit-search' />
</form>
// Encapsulate a function
// Load JSON using XHR and than append
// an options node element to the list input.
(function searchFormScoped(){
var _form = document.getElementById("search-form"),
_listNode = document.getElementById("search-data");
var xhr = new XMLHttpRequest();
xhr.open("GET", "/the_request_url.json");
xhr.responseType = "json";
xhr.onload = function loadHtmlFormList(e) {
var _data = this.response,
_datakeys = Object.keys(_data);
// loop through key id's and populate the option with
// the correct values and data attributes
for(var c=0; c < _datakeys.length; c++) {
var _opt = document.createElement("options");
// store the key values from the json as the options value
_opt.value = _data[_datakeys[c]];
// I use the data-id attribute to store key values of the json
_opt.setAttribute('data-id', _datakeys[c]);
}
// Set an event to be executed when the list value changes
_listNode.addEventListener("change", function searchOptionChanged(e) {
var _infoNode = _listNode.querySelector('option[value="' + e.target.value + '"]');
// Set the data-item attribute of the target event element of the
// string you need for your search string url to use for when the form is
// submitted, or from here you could set the action attribute, I believe.
e.target.setAttribute('data-item', 'itemID=' +_infoNode.getAttribute('data-id'));
});
}
xhr.send();
})();
So look up the id from the object and set a hidden field.
var items = {
"abc123" : 123456,
"foo": 2345
}
document.getElementById("item").addEventListener("change", function () {
var val = this.value;
var id = items[val];
if (!id) {
alert("unknown product");
}
document.getElementById("itemID").value = id ? id : '';
})
<form method="GET">
<input type="hidden" name="itemID" id="itemID" />
<label for="item">Item: <label><input type="text" id="item" />
<button>Submit</button>
</form>
`
$(function(){
$('.addLink').click(function(e){
e.preventDefault();
var content = $('.categorySelect');
var url = $("#userInput").val();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
$(link).appendTo('.sports');
});
});
Choose Category:
<select class='categorySelect'>
<option value="Sports" id="a">Sports</option>
<option value="World" id="b">World</option>
<option value="Movies" id="c">Movies</option>
</select><br />
<input type='text' id='userInput' placeholder='Enter Link Here' />
<input type='button' value='Add' class='addLink'/>
<div class='sports'>
Sports:
</div>
<div class='world'><br />
World:
</div>
<div class='movies'><br />
Movies:
</div>
</div>
`heres what i have now. when the user chooses a catergory from the dropdown menu their typed in link will show under that caterory(div class). i cant seem to figure this out.
$('.addLink').click(function () {
var content = $('.categorySelect').val().toLowerCase();
var url = $("#userInput").val();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
$(link).appendTo('.'+content);
});
jsFiddle Demo
First, you don't need event.preventDefault() because the input field doesn't have a default action that needs to be suppressed (cf. the a tag, which does).
Next, you need to grab the value of the SELECT and convert to lowercase, since that is the case of the class.
To append to the correct class, you concat the . class indicator to the name of the class extracted from the SELECT option value.
If you wanted to make the action automatic upon selection of a category, then change this:
$('.addLink').click(function () {
to this:
$('.categorySelect').change(function () {
Revised jsFiddle
Note how we can use $(this) to refer to the control that triggered the event. By using $(this), we can chain jQuery methods, e.g.
var content = $(this).val();
If all we want is the value, we can use pure javascript as it is a bit faster:
var content = this.value;
Since .toLowerCase() is pure javascript, we can still go with this.value
var content = this.value.toLowerCase();
I have wrote some working code for you, with comments included on Fiddle:
$(function(){
$('.addLink').click(function(e){
e.preventDefault();
/*
Select the value of the dropdown (lowercase the values because your
HTML classes are written lowercase) and the values of your dropdown are not.
*/
var content = $('.categorySelect').val().toLowerCase();
var url = $("#userInput").val().toLowerCase();
var link = "<a href='" + url + "'>" + "<br />" + url + "</a>";
//Save check if the user has filled in a URL.
if(url !== '')
//append URL link to the selected value of the dropdown.
$(link).appendTo('.'+content);
});
});
http://jsfiddle.net/9fc8zb4b/
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/