In my code below, I'm pulling in data from SharePoint (basically an excel spreadsheet) and displaying on my page. Checkboxes are pushed to my page using .innerHTML and are given an ID programmatically.
My question: How can I determine whether those checkboxes are checked (being that they could be different each time my app loads) ?
(Once I know what is checked, I'll display more metadata on the next page based on the checks - that part I have figured out)
$.ajax({
url: "myWebsite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
You will need a way to know how many checkboxes has been created. When creating the checkboxes, them id must have a generic name and a number, for example id="checkbox0", id="checkbox1 and so on, then write the ammount of checkboxes in some part of the html code and put it some hidden tag. Then when reading the checkboxes data read the ammount of checkboxes and do a for
function getCheckboxes(){
var ammount = parseInt(document.getElementById("checkBoxesAmmount"));
var checkbox;
for(var i = 0; i<ammount; i++){
checkbox = document.getElementById("checkbox"+i);
//do staff
}
return;
I hope this works for you c:
This bit of jQuery returns all the checked input boxes that are in a ul with the class courseList:
jQuery('ul.courseList input:checked')
If your question is asked because the course name might change (your checkbox IDs are based on the course name), I suggest switching to the course number instead (or an appropriate mix of the two).
If you want to know if your dynamically created checkboxes were checked and want to do this via Javascript before the form is submitted, then add a class to your checkboxes (say dynamicCourse) and look for get the checked checkboxes via jQuery('input.dynamicCourse:checked').
Also, your checkboxes in your example don't have a value attribute set. If you're submitting it to a backend, you'll probably want it to have some value (course number would be my suggestion from the looks of it).
Related
I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?
Here I have created a filter functionality in which user will select multiple checkbox and based on these selected checkbox ajax will get product data and will show on main page. However, my problem is whenever I select a collection name it shows only one page's data. So, could you help me to show multiple pages of data based on checkbox selection? Any help would be appreciated, Thanks.
$('.vendor_filter_item input[type="checkbox"]').click(function(){
var checkboxes = document.querySelectorAll('.vendor_filter_item input[type="checkbox"]:checked');
for (var i = 0; i < checkboxes.length; i++) {
var check_value = checkboxes[i].value;
$.ajax({
url:check_value,
type:'GET',
success: function(data) {
var content = $('<div>').append(data).find('.collection_all_product #product-grid ');
if($('.CollectionInner__data').html() == ""){
$('.CollectionInner__data').html($('.js_inner_product').html());
}
$('.js_inner_product').html("");
$('.js_inner_product ').append( content );
$('.js_inner_product').show();
$('.collection_all_product').hide();
}
});
}
});
So I am trying to create a function in which I have various checkboxes of territories. The only thing is that I have pages for only some of the territories. So when a user selects a territory and it has a link to a page, then on submit it will take the user to that page. If the checkbox does not have a link then it will go to contact page. But if they select more than one territory and one of them has a link, it should still take them to that same contact page. The second part is that I want the selections to be parsed to the url to go to the contact page which will be a contact form 7 form so it auto fills the territory they selected.
so far I have created a function which recognizes how many checkboxes have been selected. I tried to add links and identify if those links that were selected with the checkbox. Im not sure if it is recognizing it with its corresponding element.
Html
<a href="https://corporate.territory.place/advertising-sandiego"
id="salesURL"><input type="checkbox" name="territories" value="San
Diego, CA">San Diego, CA</a>
<a href="https://corporate.territory.place/advertising-orlando"
id="salesURL"><input type="checkbox" name="territories"
value="Orlando, FL">Orlando, FL</a>
<a href="#" id="nosalesURL"><input type="checkbox"
name="territories" value="Miami, FL">Miami, FL</a><br>
<button onclick="printChecked()">Click here</button>
jquery
function printChecked(){
var items=document.getElementsByName('territories');
/*below list the value of the selections*/
var selectedItems="";
for(var i=0; i<items.length; i++){
if(items[i].type=='checkbox' && items[i].checked==true)
var itemz = selectedItems+=items[i].value+" ";}
var n = $("input[name=territories]:checked").length;/*Counts
number of box selected*/
var salesUrl =
document.getElementById("salesURL").getAttribute("href");
var salesID =
document.getElementById("salesURL").getAttribute('id');
if( n >= 1 && salesID == "salesURL"){
$("#info").html("Selected only 1" + " " + salesUrl+" "+itemz);
}else if(n >= 1 && salesID == "nosalesURL"){
$("#info").html("Go to contact sales");
}else{
$("#info").html("none selected");
}
}
Here's a link to where I am building it out!
For some reason when I try to set the condition for more than one selected it gives me the result of the first condition. I want the function to recognize the checkbox and determine if they have a url. if more than one then go to this page. it only one selected and it has a url then go to another page. etc
Since you only want to use the specific URL if 1 checkbox is checked, you can simplify the logic by only looking for that event. All other scenarios will result in the contact page. Additionally, id should be unique for each element, but they aren't even required here so you should remove them (or make them unique).
I added an additional function for handling the redirects.
JS
<script type="text/javascript">
function printChecked() {
var items = $("input[name=territories]:checked"),
url = "contact.html";
if (items.length == 1) {
var href = items.parent("a").attr("href");
if ($.trim(href).length > 1) {
url = href;
}
}
redirect(url);
}
function redirect(url) {
window.location = url;
}
</script>
This is the solution I arrived at.
$( "#territorybtn" ).click(function() {
var places = $("input[name=territories]:checked");
var clickTerritory = $("input[name=territories]:checked").val();
var clickTerritoryUrl = "https://privatecontractor.com/loaction-"+clickTerritory;
var shortClickTerritoryUrl = clickTerritoryUrl.substr(0,
clickTerritoryUrl.length-2);
var saleID = places.parent("a").attr("class");
/*below list the value of the selections*/
var selectedItems="";
for(var i=0; i<places.length; i++){
if(places[i].type=='checkbox' && places[i].checked==true)
var itemz = selectedItems+=places[i].value+" ";}
/*Conditions*/
if (places.length == 1 && saleID == "salesURL"){
window.location = shortClickTerritoryUrl;
}else if(places.length == 0){
alert(places.length +" "+ "Choose a Territory");
}else{
window.location = "https://privatecontractor.com/contact-sales/?textarea=" + itemz;
}
});
So I am checking to see if the checkboxes are checked and their values. Next, I am looping the values if more than one checkbox is selected so when I parse it to the url for the contact form it will list them in the form.
I placed the condition so that if one checkbox is checked and its parent anchor has the class then it would go to the url created based on its value. If more than one is selected then they will go to contact form with the values added to the url.
For the second part of parsing the checked box values to the url to send to contact form i used a script from this awesome gentleman. https://wplearninglab.com/contact-form-7-get-value-from-url/
Thanks for your help #johnniebenson.
How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});
I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?
<!-- Javascript -->
<script>
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->
}
<script>
foreach($cityrows as $cityrow){
echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location'];
echo '<br>';
}
echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
This is a variation to get all checked checkboxes in all_location_id without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>