Jquery out put values issue - javascript

I'm having some issues with jquery.
I have a variable amount of libox's that have specific values in them.
I want to grab the data and on clikc out put it to a text area. but I'm having some problems with it.
here is my code:
$(".bottomtri.single_add_to_cart_button").click(function() {
var slival = $("#mixers li .infora h3").text(),
slivalmix = $("#mixers li .mix-value").text(),
slivalimg = $("#mixers li .color-img").html(),
slivaltotal = slivalimg + slival + slivalmix;
$(".addon.addon-custom-textarea").val(slivaltotal);
});
with this snippet might out put is just mashing everything together and its also adding up the numbers.
What I want it to do is go through each one and out put it like a list.
so it would have an out put like
h3 mix-value color-img
h3 mix-value color-img
h3 mix-value color-img
h3 mix-value color-img

You need to loop over the slide elements, and build up an array of strings. Then after the loop you can join the items in the array, and separate them with line breaks. You also need to add seperaters when you concatenate the values.
$(".bottomtri.single_add_to_cart_button").click(function() {
var sliStrings = [];
$("#mixers li").each(function () {
var slival = $(".infora h3", this).text(),
slivalmix = $(".mix-value", this).text(),
slivalimg = $(".color-img", this).html(),
sliStrings.push(slivalimg + " " + slival + " " + slivalmix);
});
$(".addon.addon-custom-textarea").val(sliStrings.join('\n'));
});

You want spaces between the values, and you want numbers to be treated like text, then you have to put spaces in the output, this will also avoid numbers being added together
slivaltotal = slivalimg + " " + slival + " " + slivalmix

Related

HTML: New Line not working

I basically just want to display each entry of local storage on a new line inside a list element.
Here is my JS:
if ( counter == 1 ){
var json = JSON.parse(localStorage.getItem( localStorage.key( i )))
var textm = 'Entry:'+json.Entry+'\n Exercise: '+json.Exercise+'\n Date:'+json.Date+'\n Start: ' +json.Start+'\n End: '+json.End+'\n Calories: '+json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(textm));
ul.appendChild(li);
};
Very long i know, but this is the output I receive:
What is the reasoning for this? Do I not use line breaks right? or could it potentially be my CSS?
Unless you are using <pre> elements, or the equivalent CSS formatting, browsers treat newline characters as spaces, and condense multiple whitespace characters down to a single space. To have your fields appear on separate lines you need to insert <br> line break elements rather than newline characters. (Or use a nested list, or wrap each "line" in a <p> element, or whatever. But just using <br> elements is simplest.)
Except that because you are setting the text with .createTextNode() simply including "<br>" in your string would display those characters rather than creating an element. The simplest solution to this is to set the .innerHTML of your <li> element rather than using .createTextNode():
if (counter == 1) {
var json = JSON.parse(localStorage.getItem(localStorage.key(i)))
var textm = 'Entry:' + json.Entry + '<br> Exercise: ' + json.Exercise + '<br> Date:' + json.Date
+ '<br> Start: ' + json.Start + '<br> End: ' + json.End + '<br> Calories: ' + json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.innerHTML = textm;
ul.appendChild(li);
}
As an aside, you don't need a semicolon after the closing } of an if block. Also, assuming the above code is contained in a loop, it would be more efficient to move the line with var ul = document.getElementById("list"); to before the loop, so that you only have to lookup that element once instead of doing it on every loop iteration.
In html as W3Schools says,for breaking line we must use <br> instead of \n(or any other character).
I hope this helps :)
Here is your soultion
You need to create element. you can't pass it as a string
Example : document.createElement("br");
if ( counter == 1 ){
var json = JSON.parse(localStorage.getItem( localStorage.key( i )))
var textm = 'Entry:'+json.Entry+document.createElement("br")+' Exercise: '+json.Exercise+'\n Date:'+json.Date+'\n Start: ' +json.Start+'\n End: '+json.End+'\n Calories: '+json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(textm));
ul.appendChild(li);
};
Update your text concatenation with <br/> instead of \n like below.
var textm = 'Entry:'+json.Entry+'<br/> Exercise: '+json.Exercise+'<br/> Date:'+json.Date+'<br/> Start: ' +json.Start+'<br/> End: '+json.End+'<br/> Calories: '+json.Calories;
li.innerHTML = textm;

Grouping selectors in 1 action

I'm having a simple issue with grouping jQuery selectors in 1 action.
For example I have a list of variables like:
var searchresults = '#search-results';
var event_two = '#event-two';
var competition_three = '#competition-three';
var apparatus_four = '#apparatus-four';
After triggering on change event I have something like this:
$("#event_two, #competition_three, #apparatus_four").empty();
No problem is I can't get it working. I've tried already in a lot of different ways.
This is how the code snippet of the first part of my code:
$(document).on('change', '#discipline-one', function() {
var discipline = $(this).val();
// event_two.empty();
// competition_three.empty();
// apparatus_four.empty();
$("#event_two, #competition_three, #apparatus_four").empty();
$("#event_two").append("<option selected='true' disabled='disabled'>Please select an event</option>");
$("#competition_three").append("<option selected='true' disabled='disabled'>Please choose from above</option>");
$("#apparatus_four").append("<option selected='true' disabled='disabled'>Please choose from above</option>");
$("#event_two").attr("disabled",true);
$("#competition_three").attr("disabled",true);
$("#apparatus_four").attr("disabled",true);
$.get("getEvents.php?discipline=" + discipline, function(data) {
var vals = jQuery.parseJSON(data);
if(data) {
$("#event_two").attr("disabled",false);
$("#event_two").attr("autofocus",true);
}
if($.isArray(vals['Event'])) {
$.each(vals['Event'], function(k,v){
$("#event_two").append("<option value='"+v['id']+"'>" + v['name'] + "</option>");
});
} else {
$("#event_two").append("<option value='"+vals['Event']['id']+"'>" + vals['Event']['name'] + "</option>");
}
});
});
Thank you in advance.
I think you have a typo:
Here you say:
$("#event_two, #competition_three, #apparatus_four").empty();
Where you define id's with underscores.
Here you say:
var searchresults = '#search-results';
var event_two = '#event-two';
var competition_three = '#competition-three';
var apparatus_four = '#apparatus-four';
Where your id's doesn't contain underscores.
I think you mean: (UPDATE)
$(event_two + ', ' + competition_three + ', ' + apparatus_four).empty();
Like #VDesign said, you define ID's with underscores, but in your variables, you have hyphens. So the following won't work:
$("#event_two, #competition_three, #apparatus_four").empty();
But when you want to select multiple objects, you have to have one big string with commas, like so:
$(event_two + ',' + competition_three + ',' + apparatus_four).empty();
See http://api.jquery.com/multiple-selector/ for more details on multiple selectors.
You could even do something like this:
$([ event_two, competition_three, apparatus_four ].join(',')).empty();

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

js/jquery iterate through html elements to dynamically build a string

I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"

Removing rows that do not contain search-term with jQuery

I'm using the following JQuery to filter rows on a datatable, which works fine...
yuiDtFilter = function(tableDivId, filter) {
//custom jQuery function defines case-insensitive fn:Contains, use default fn:contains for case-sensitive search
jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
$("#" + tableDivId + " .yui-dt-data").find('tr').hide();
$("#" + tableDivId + " .yui-dt-data").find('td:Contains("' + filter + '")').parents('tr').show();
}
However I have a need for the filter work in the opposite way. I need it to remove rows that don't match the search terms.
I've found out that I need to use 'not()', but I've spent most of the day in vain trying to get it to work (using every example I can find).
I've tried many variations of -
$("#" + tableDivId + " .yui-dt-data")
.find(:not(('td:Contains("' + filter + '")'))
.parents('tr').remove();
Could anyone give me a hand using my code as a starting point?
Try
$("#" + tableDivId + " .yui-dt-data").find('td').not(':contains("' + filter + '")').parents('tr').remove();
or
$("#" + tableDivId + " .yui-dt-data").find( 'td:not(:contains("' + filter + '"))' ).parents('tr').remove()
Remove row from HTML table that doesn't contains specific text or string using jquery.
Note: If there are only two column in HTML table, we can use "last-child" attribute to find.
*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:last-child");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.
Passing column index with "nth-child(column index)"
$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:nth-child(2)");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: "DrivePilot" is nothing but text or string

Categories