I have tested every solution I have found on Internet, but none of them works.
I have this HTML:
<h4>Códigos disponibles:<span id="codesQuantity">#Model.ExternalCodesForThisProduct</span></h4>
And this Javascript:
$('#eCodesFrm').on('submit', function (e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var availableCodes = $("#codesQuantity");
var totalCodesUsed = 0;
alert(availableCodes);
$('#eCodesFrm *').filter(':input').each(function () {
if (this.name.match(/.Quantity$/)) {
totalCodesUsed = totalCodesUsed + parseInt(this.value, 10);
}
});
But availableCodes is [object Object].
What am I doing wrong?
If you need the inner element try .html(). As long as it's plain text in there there shouldn't be a problem.
To get the text inside the <span> use .text():
jQuery("#codesQuantity").text() //or $("#codesQuantity").text() if $ is jQuery in your code.
The problem here is that you're assigning a jQuery object to your variable, and not the content of the element. To extract the text inside the <span>, you should use either .html() or .text(), and do this instead:
var availableCodes = $("#codesQuantity").text();
Related
My html markup is looking like this : <div id="somediv"> [whitespace] text</div> and I'm adding this value like inside an input element like this:
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text());
jQuery('input[name="search"]').keyup();
});
This works fine but the problem is that is adding the value with the whitespaces and I don't want this.
I've found this jquery method jQuery.trim() which seems to remove all the whitespaces but I don't know how can I use it inside my actual function.
Can someone give me some suggestions on how achieve this ?
Chain the method to the text
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text().trim());
jQuery('input[name="search"]').keyup();
});
Use trim(). Like:
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text().trim());
jQuery('input[name="search"]').keyup();
});
I recommend you "cache" your jQuery calls, so I did it by using oSearch. (Line 1)
then to answer your jQuery.trim question... do it like this
var oSearch = jQuery('input[name="search"]');
jQuery('.votefilters span a:first').on('click', function(event) {
var text = jQuery('.myo-poll-bar.firstoption').text();
text = jQuery.trim( text );
oSearch.val( text );
oSearch.keyup();
});
jQuery.trim('yourtext') similar to this:
jQuery('.votefilters span a:first').on('click', function (event) {
var $input = jQuery('input[name="search"]');
var newText = jQuery('.myo-poll-bar.firstoption').text();
var trimmedText = jQuery.trim(newText);
$input.val(trimmedText);
$input.keyup();
});
DEMO - Using jQuery.trim();
I want to get the content of multiple Spans. Here is my code:
http://jsfiddle.net/4XumV/
It's supposed to give me "111, 222, 333, 444". It gives me "undefined" instead.
What's wrong with my code?
Well, you weren't actually getting the innerHTML property, you were getting an undefined html property. Change it to innerHTML and it will work.
http://jsfiddle.net/4XumV/1/
This should work:
$(function()
{
var allLatestNews = $("#main").find('span');
$.each(allLatestNews, function(i,val){
alert($(val).text());
});
});
I was wondering WHY your code wasn't working and JQuery does return an array of elements from the selector, this could have also worked:
for(var i = 0; i < allLatestNews.length; i++)
{
alert($(allLatestNews[i]).text());
}
First wrap the element as a JQuery object and then querying text() not html, which is accessed by a function not a property.
Your updated fiddle: http://jsfiddle.net/4XumV/9/
You seem to be confusing jquery's html with innerHTML.
You can either use innerHTML:
http://jsfiddle.net/4XumV/3/
alert(allLatestNews[i].innerHTML);
or jquery's html:
http://jsfiddle.net/4XumV/5/
alert(allLatestNews.eq(i).html());
Try this it should work
allLatestNews.each(function()
{
alert($(this).html());
});
var $elms = $('#main').find('span');
$elms.each(function(){ alert($(this).text()); });
http://jsfiddle.net/4XumV/2/
This is working
var allLatestNews = $("#main").find('span');
$.each(allLatestNews ,function( index , value){
console.log($(value).html());
});
instead of console.log($(value).html()); you can write alert($(value).html());
The property of a DOM element to return the inner HTML is named innerHTML not html
allLatestNews[i].innerHTML
Or using jQuery
$(allLatestNews[i]).html()
Updated JS Fiddle
you can also use this
var allLatestNews = $(this).find("#main span");
for(var i = 0; i < allLatestNews.length; i++)
{
alert(allLatestNews[i].innerHTML);
}
I have the following HTML snippet:
<span class="target">Change me <a class="changeme" href="#">now</a></span>
I'd like to change the text node (i.e. "Change me ") inside the span from jQuery, while leaving the nested <a> tag with all attributes etc. intact. My initial huch was to use .text(...) on the span node, but as it turns out this will replace the whole inner part with the passed textual content.
I solved this with first cloning the <a> tag, then setting the new text content of <span> (which will remove the original <a> tag), and finally appending the cloned <a> tag to my <span>. This works, but feels such an overkill for a simple task like this. Btw. I can't guarantee that there will be an initial text node inside the span - it might be empty, just like:
<span class="target"><a class="changeme" href="#">now</a></span>
I did a jsfiddle too. So, what would be the neat way to do this?
Try something like:
$('a.changeme').on('click', function() {
$(this).closest('.target').contents().not(this).eq(0).replaceWith('Do it again ');
});
demo: http://jsfiddle.net/eEMGz/
ref: http://api.jquery.com/contents/
Update:
I guess I read your question wrong, and you're trying to replace the text if it's already there and inject it otherwise. For this, try:
$('a.changeme').on('click', function() {
var
$tmp = $(this).closest('.target').contents().not(this).eq(0),
dia = document.createTextNode('Do it again ');
$tmp.length > 0 ? $tmp.replaceWith(dia) : $(dia).insertBefore(this);
});
Demo: http://jsfiddle.net/eEMGz/3/
You can use .contents():
//set the new text to replace the old text
var newText = 'New Text';
//bind `click` event handler to the `.changeme` elements
$('.changeme').on('click', function () {
//iterate over the nodes in this `<span>` element
$.each($(this).parent().contents(), function () {
//if the type of this node is undefined then it's a text node and we want to replace it
if (typeof this.tagName == 'undefined') {
//to replace the node we can use `.replaceWith()`
$(this).replaceWith(newText);
}
});
});
Here is a demo: http://jsfiddle.net/jasper/PURHA/1/
Some docs for ya:
.contents(): http://api.jquery.com/contents
.replaceWith(): http://api.jquery.com/replacewith
typeof: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
Update
var newText = 'New Text';
$('a').on('click', function () {
$.each($(this).parent().contents(), function () {
if (typeof this.tagName == 'undefined') {
//instead of replacing this node with the replacement string, just replace it with a blank string
$(this).replaceWith('');
}
});
//then add the replacement string to the `<span>` element regardless of it's initial state
$(this).parent().prepend(newText);
});
Demo: http://jsfiddle.net/jasper/PURHA/2/
You can try this.
var $textNode, $parent;
$('.changeme').on('click', function(){
$parent = $(this).parent();
$textNode= $parent.contents().filter(function() {
return this.nodeType == 3;
});
if($textNode.length){
$textNode.replaceWith('Content changed')
}
else{
$parent.prepend('New content');
}
});
Working demo - http://jsfiddle.net/ShankarSangoli/yx5Ju/8/
You step out of jQuery because it doesn't help you to deal with text nodes. The following will remove the first child of every <span> element with class "target" if and only if it exists and is a text node.
Demo: http://jsfiddle.net/yx5Ju/11/
Code:
$('span.target').each(function() {
var firstChild = this.firstChild;
if (firstChild && firstChild.nodeType == 3) {
firstChild.data = "Do it again";
}
});
This is not a perfect example I guess, but you could use contents function.
console.log($("span.target").contents()[0].data);
You could wrap the text into a span ... but ...
try this.
http://jsfiddle.net/Y8tMk/
$(function(){
var txt = '';
$('.target').contents().each(function(){
if(this.nodeType==3){
this.textContent = 'done ';
}
});
});
You can change the native (non-jquery) data property of the object. Updated jsfiddle here: http://jsfiddle.net/elgreg/yx5Ju/2/
Something like:
$('a.changeme3').click(function(){
$('span.target3').contents().get(0).data = 'Do it again';
});
The contents() gets the innards and the get(0) gets us back to the original element and the .data is now a reference to the native js textnode. (I haven't tested this cross browser.)
This jsfiddle and answer are really just an expanded explanation of the answer to this question:
Change text-nodes text
$('a.changeme').click(function() {
var firstNode= $(this).parent().contents()[0];
if( firstNode.nodeType==3){
firstNode.nodeValue='New text';
}
})
EDIT: not sure what layout rules you need, update to test only first node, otherwise adapt as needed
Im very new to javascript and jquery so please bear with me.
Here's my code: http://jsfiddle.net/94MnY/1/
Im trying to get the values of each hidden field inside the div.
I tried
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
var totalHidden = 7;
for(var i=0; i<totalHidden; i++) {
alert($("#hiddenField hidden").html());
}
});
});
but the value Im getting is null.
I also wanna know how to get the total number of html elements inside a div. In my case how am I gonna get the total number hidden field inside the div. I assigned the value of totalHidden = 7 but what if I dont know total number of hidden fields.
Please help. Thanks in advance.
$('#hiddenField hidden') is attempting to access an actual <hidden> tag that is a child of #hiddenField
Try this instead. What you want to use is the input[type=hidden] selector syntax. You can then loop through each of the resulting input fields using the jQuery.each() method.
If you want to iterate over the <input> elements and alert each value try this:
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$('#hiddenField input').each(function() {
alert(this.value);
});
});
});
http://jsfiddle.net/94MnY/8/
Here it is.
Basically, you are looking for .each(). I removed a few input fields because so many alert messages are annoying. Also added in the selector the type hidden to avoid getting your last input field.
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$('input[type="hidden"]').each(function(i){
alert($(this).attr('value'))
})
});
});
To stick to what you already have - but with few modifications:
DEMO
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
var totalHidden = $('#hiddenField input[type=hidden]').length; // get number of inputs
for(var i=0; i<totalHidden; i++) {
alert($("#hiddenField input[type=hidden]").eq(i).val());
}
});
});
You can actually just create an array of those hidden elements using query and loop through them and alert their values.
I have put a jsfiddle for you to see
http://jsfiddle.net/94MnY/4/
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$("#hiddenField input[type='hidden']").each(function(i, e){
alert($(this).val());
});
});
});
Try
$('#hiddenfield input[type=hidden]').each(function(){
alert(this.val());
});
Why is line 10 returning null?
http://pastie.org/720484
it works with line 40
You do not seem to have a proper grasp of the siblings() operator. You also were not utilizing jQuery's val() function and were missing periods on some of your class names. To locate the address1 class you would need to do the following:
var $checkbox = jQuery(this);
$checkbox.parent().siblings('.formField').find('.address1');
Also, you would want the alert to be
alert($checkbox.parent().siblings('.formField').find('.address1').val());
to alert the value of the input box.
FIXED AND OPTIMIZED VERSION:
function update_address(eventObject) {
var $checkbox = jQuery(this);
var $siblings = $checkbox.parent().siblings('.formField');
if ($checkbox.attr('checked')) {
$siblings.find('.address1').val($('.hidden_address1').val());
$siblings.find('.address2').val($('.hidden_address2').val());
$siblings.find('.city').val($('.hidden_city').val());
$siblings.find('.state').val($('.hidden_state').val());
$siblings.find('.zip').val($('.hidden_zip').val());
$siblings.find('.province').val($('.hidden_province').val());
$siblings.find('.country').val($('.hidden_country').val());
} else {
$siblings.find('.address1').val('');
$siblings.find('.address2').val('');
$siblings.find('.city').val('');
$siblings.find('.state').val('');
$siblings.find('.zip').val('');
$siblings.find('.province').val('');
$siblings.find('.country').val('');
}
}
try fetching the input:text's .val() instead
On line 9, shouldn't it be var checkbox = $(this); instead? I've not seen the jQuery() function used like that.
Because <input class="address1"/> is not a sibling of <input id="parent_sameAsBefore"/>. I think you want:
checkbox.parent().parent().find('.address1');
Why not just go with finding the form fields using absolute path?
Unless your DOM is very convoluted (and you need relative paths), I would prefer this approach myself.
Also use .val() to get and set values.
function update_address(eventObject) {
if($(this).attr('checked')) {
$('#parent_address1').val($('hidden_address1').val());
$('#parent_address2').val($('hidden_address2').val());
$('#parent_city').val($('hidden_city').val());
$('#parent_state').val($('hidden_state').val());
$('#parent_zip').val($('hidden_zip').val());
$('#parent_province').val($('hidden_province').val());
$('#parent_country').val($('hidden_country').val());
}
else {
$('#parent_address1').val("");
$('#parent_address2').val("");
$('#parent_city').val("");
$('#parent_state').val("");
$('#parent_zip').val("");
$('#parent_province').val("");
$('#parent_country').val("");
}
}
Note, seems to be a bug in the original code in line 15:
checkbox.siblings('.tate').value = $('hidden_state').value;
Should be:
checkbox.siblings('.state').value = $('hidden_state').value;
alert(checkbox.siblings('.address1').html() ); // This should be
alert(checkbox.parent().siblings('.address1').html() );
//Checkbox does not have siblings
Line 10