how to gather data from different pages? - javascript

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();
}
});
}
});

Related

Append a Nodelist result in a form

I have this function:
function selectCheckedAnswer(){
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
for (let i = 0; i < checkbox_checked.length; i++) {
let item = checkbox_checked[i];
form.appendChild(item);
}
}
It is not working as expected. When debugging, there are generated one form to each checkbox checked. (because I inserted the form inside of the For loop, I know)
When I debug the code above, 2 forms are being sent to the controller
image here
...but I just get 1 of the forms and 1 checked checkbox:
image here
What I need is to send only one form with the checkboxes selected to the controller.
I think you are looking for this:
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
checkbox_checked.forEach(element => {
form.innerHTML += element.innerHTML;
});

How to create a checkbox that goes to a certain link under specific conditions

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 I capture checkboxes that I'm creating programmatically?

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).

Getting multiple selected checkbox values in a string in javascript and PHP

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>

Submitting a form + grid in ExtJS 4

I have an Ext.form.Panel containing a grid and some text fields for editing each row in the grid. It is very similar to this: http://dev.sencha.com/deploy/ext-4.0.2a/examples/writer/writer.html , only that there is no AJAX involved; my data store is local.
How can I submit the grid's rows via a standard POST?
If I simply do myForm.submit(), there are two issues:
The fields for editing the grid's rows are being validated. They should be ignored when submitting the form.
No data from the grid is being submitted.
The only solution I see is to somehow prevent the fields from being validated and create some hidden fields containing the data from each row. Is there any better option?
Thank you in advance!
Here's the solution I used:
For ignoring certain fields from the form upon submitting, I've overwritted the getFields() method of the form. Nasty, I know. In the code below, the fields with an 'ignoreInMainForm' property will be ignored.
Ext.getCmp('myForm').getForm().getFields = function() {
var fields = this._fields;
if (!fields) {
var s = [],
t = this.owner.query('[isFormField]');
for (var i in t) {
if (t[i]['ignoreInMainForm'] !== true) {
s.push(t[i]);
}
}
fields = this._fields = Ext.create('Ext.util.MixedCollection');
fields.addAll(s);
}
return fields;
}
For submitting the grid's data, I encode all the rows in a single JSON object that I add in the form's baseParams.
var myItems = myStore.getRange();
var myJson = [];
for (var i in myItems) {
myJson.push({
'a': myItems[i].get('a'),
'b': myItems[i].get('b'),
...
});
}
Ext.getCmp('formHiddenId').setValue(Ext.encode(myJson ));
That partially worked for me - in ExtJS 4.0.2a, I couldn't add to the baseParams, so instead I triggered the send handler to instead do:
function prepareToSendForm(a, b) {
var myItems = Ext.getCmp('grid-links').store.getRange();
var myJson = [];
for (var i in myItems) {
myJson.push({
'title': myItems[i].get('title'),
'url': myItems[i].get('url'),
'refreshes': myItems[i].get('refreshes')
});
}
//Update the hidden field to be the JSON of the Grid
for (var i=0, len=Ext.getCmp('roomCreateForm').getForm()._fields.items.length; i<len; i++) {
var item = Ext.getCmp('roomCreateForm').getForm()._fields.items[i];
if (item.name=='roomLinks') {
Ext.getCmp('roomCreateForm').getForm()._fields.items[i].inputEl.dom.value=Ext.encode(myJson);
break;
}
}
Ext.getCmp('roomCreateForm').submit();
}
Which worked lie a charm (but isn't very plug-and-play). I had to create a hidden field (named roomLinks above) in the form, and the second for loop above finds that and replaces the value with the JSONed results.

Categories