I'm using Jquery to find the users email in my site, but I don't know how can I find a email for users with the same name.
Using this code, my variable return just one value for string.
var mail = $("#dat").contents().find("td:contains('" + name + "')" ).siblings("td").eq(1).text();
How can I get all strings that match in this find event?
Thanks!
EDIT: My code don't have any HTML markup for data, I'm using Google Spreadsheet to get the values.
Imagine there is one table with:
<tr><td>Name 1</td><td>mail1</td></tr>
<tr><td>Name 2</td><td>mail2</td></tr>
<tr><td>Name 1</td><td>mail3</td></tr>
If I use find containing "Name 1", my variable should return mail1, mail3.
To get the second column of all matching rows, use nth-child.
To get all values in an array, you can use map() and get()
var name = 'Name 1';
var mail = $("#dat").contents()
.find("td:contains('" + name + "')" )
.siblings("td:nth-child(2)")
.map(function() {
return $(this).text();
}).get()
document.body.innerHTML = '<pre>' + JSON.stringify(mail, 0, 4) + '</pre>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="dat">
<tr><td>Name 1</td><td>mail1</td></tr>
<tr><td>Name 2</td><td>mail2</td></tr>
<tr><td>Name 1</td><td>mail3</td></tr>
</table>
The query for find could be more specific as well, that way using siblings wouldn't be neccessary
var mail = $("#dat").contents()
.find("tr:has(td:contains('" + name + "')) td:nth-child(2)" )
.map(function() {
return $(this).text();
}).get()
You should change you code a little, to:
mail = $("#dat").contents().find("td:contains('" + name + "')" ).next().text();
Check demo - Fiddle
Related
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"
I'm having some problems when trying to add a class to a variable and then append this to another div. When I do this, the text appears but without the class I am trying to add to it. I am doing all of this with jQuery.
This is the code:
var names = $(this).attr('name');
var description = $(this).attr('description');
var url = $(this).attr('url');
$(names).addClass("nam");
$(div1).append( names + " " + description + " " + url);
});
I guess I am doing something wrong but can't see where.
You are creating a jQuery wrapper for name and adding a class to it but then you are appending the previous string reference instead of the jQuery wrapper to which the class was added.
Also you can't add class to a text node so try wrapping it with a span element(if name is not a html content like <span>some name</span>)
var names = $('<span />', {
text : $(this).attr('name'),
'class' : 'nam'
})
var description = $(this).attr('description');
var url = $(this).attr('url');
$(div1).append( names).append( " " + description + " " + url);
});
First off for this answer I am assuming we're using an xml string of the format you provided in your comment on op. Note - I did correct the syntax of the string to remove the extraneous semi colons.
var xmlstring = '<Blogs> <blog name="number1" description="1" url=" 1.com/"/> <blog name="number2" description="2" url="2.com/"/> <blog name="number3" description="3" url="3.com;" />" </Blogs>'
Now we can parse this string as expected into a jQuery object and use mostly as expected:
var $doc = $($.parseXML(xmlstring));
I'm assuming in your original example that this blog refers to one of these sub blogs so I'm going to say for my example:
var $this = $doc.find("blog:eq(2)");//the blog name=number3 in your example
//OR
var $this = $(this);//useful so we dont keep rewrapping
Okay so now we have our blog ($this) and we can append the contents to div1 as follows:
var names = $("<span>", {text:$this.attr('name'), 'class': 'nam'});
var description = $this.attr('description');
var url = $this.attr('url');
$(div1).append( names, description + " " + url);//as names is a span element
I tested this on an empty div and it produced the following outerhtml:
"<div><span class="nam">number3</span>3 3.com;</div>"
Hope this helped, I tried to explain steps because I'm not sure where what you're doing was deviating.
I have a string with multiple elements with id's like below:
var data = "<div id='1'></div><input type='text' id='2'/>";
Now I'm using this regex to find all the id's in the string:
var reg = /id="([^"]+)"/g;
Afterwards I want to replace all those id's with a new id. Something like this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');
I want reg2, as seen above, to return the value of the id's.
I'm not too familiar with Regular Expressions, so how can I go about doing this?
Instead of using regex, parse it and loop through elements. Try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = document.createElement("div"),
i, cur;
div.innerHTML = data;
function updateId(parent) {
var children = parent.children;
for (i = 0; i < children.length; i++) {
cur = children[i];
if (cur.nodeType === 1 && cur.id) {
cur.id = cur.id + "_" + numCompare;
}
updateId(cur);
}
}
updateId(div);
DEMO: http://jsfiddle.net/RbuaG/3/
This checks to see if the id is set in the first place, and only then will it modify it.
Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).
Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.
To get the get the updated HTML, use div.innerHTML.
With jQuery, you can try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = $("<div>"),
i, cur;
div.append(data);
div.find("[id]").each(function () {
$(this).attr("id", function (index, attr) {
return attr + "_" + numCompare;
});
});
DEMO: http://jsfiddle.net/tXFwh/5/
While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.
References:
.children: https://developer.mozilla.org/en-US/docs/DOM/Element.children
.nodeType: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType
jQuery.find(): http://api.jquery.com/find/
jQuery.attr(): http://api.jquery.com/attr/
jQuery.each(): http://api.jquery.com/each/
Try using
.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Regex probably isn't the right way to do this, here is an example that uses jQuery:
var htmlstring = "<div id='1'></div><input type='text' id='2'/>";
var $dom = $('<div>').html(htmlstring);
$('[id]', $dom).each(function() {
$(this).attr('id', $(this).attr('id') + '_' + numCompare);
});
htmlstring = $dom.html();
Example: http://jsfiddle.net/fYb3U/
Using jQuery (further to your commments).
var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).
Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/
I am working on a simple form demo and i would like the input to display in a below the form. Currently i have it populating in the console. How do i may it display in the div when i click the submit button?
My code:
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$('#firstName').val();
$('#lastName').val();
$('#phoneNumber').val();
$('#address').val();
console.log($('#firstName').val());
console.log($('#lastName').val());
console.log($('#phoneNumber').val());
console.log($('#address').val());
});
});
Well, you're currently not putting the values anywhere but into the console.log.
I would expect to see something like (let's call your div you want the values to go to, "output"):
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
// Borrowing from another response, this is better
// Putting these in variables protects you from
// 1) accidentally modifying your form values
// 2) invalid input, if you add some basic checks, like
// testing to see if the length is > 0, doesn't contain
// bad characters, etc.
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
phone = $('#phoneNumber').val(),
address = $('#address').val();
// get a reference to the div you want to populate
var $out = $("#output");
// This is a better way of dealing with this
// because every call to .append() forces DOM
// reparsing, and if you do this too often, it can cause
// browser slowness. Better to put together one string
// and add it all at once.
$out.html("<p>" + firstName + "</p>" +
"<p>" + $('#lastName').val() + "</p>" +
"<p>" + $('#phoneNumber').val() + "</p>" +
"<p>" + $('#address').val() + "</p>");
});
});
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$(this).after('<div>First name: '+$('#firstName').val()+'<br>'+
'Last name: '+$('#lastName').val()+
' .... ');
});
});
First of all, the four lines where you read the .val() but don't do anything with it are essentially wasted cycles, you probably meant to store them in variables:
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phoneNumber = $('#phoneNumber').val();
var address = $('#address').val();
To show them in some other element, use the setter version of .val() for input types, or .text() if it's a display type (div, span, etc):
$('#someOtherElement').text(firstName + '\n' +
lastName + '\n'
phoneNumber + '\n'
address);
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
//$('#firstName').val();
//$('#lastName').val();
//$('#phoneNumber').val();
//$('#address').val();
var htmlContent = $('#firstName').val() + '<br />' + $('#lastName').val() + '<br />' + $('#phoneNumber').val() + '<br />' + $('#address').val();
$('#ID_OF_YOUR_DIV_HERE').html(htmlContent);
});
});
Maybe this is what you're after??
You can add it to a div you want with .append(), for example
$("#divYouWantToAddTo").append($('#firstName'));
I don't know where to start... What is all that $('#....').val() in the middle there, wasting time only to throw away the result..?
What is wrong with document.getElementById('...').value instead of wasting time creating an entire jQuery object just to access something trivial?
Adding text to a node is as simple as container.appendChild(document.createTextNode(sometext)); - and if you want to have newlines between them you can also do container.appendChild(document.createElement('br'));.
There is no need for jQuery here at all...
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