Get NaN instead of id value in jquery - javascript

I try to get element id using jquery, but instead of id I have a NaN, can anybody help me?
<button class="editResume" type="button" id="editResume1">Edit</button>
$(function () {
$(".editResume").click(function () {
var id = parseInt($(this).attr('id').substring(6));
alert(id);
});
});

You should use 10 instead of 6 since the number is staying at 10th index:
var id = parseInt($(this).attr('id').substring(10));
Fiddle Demo
Another alternative solution here is to apply regex:
$(function () {
$(".editResume").click(function () {
var id = parseInt($(this).attr('id').match(/\d+$/),10);
alert(id);
});
});
Fiddle Demo

var id = parseInt($(this).attr('id').substring(10));
But why do you want do it in this way?

If you want to append some (number or id of the table) in the attribute id always seperate it with some character (say -).
eg. id='editResume-1'. Then in jQuery.
var id = $(this).attr('id').split('-').pop() will give back your number. It works for every case even if you id is id='edit1Resume-1 or id='5-edit-resume-1 or any. Remember to append your required number/id at the end seperated by -
I always prefer this way. May be useful (yn)

If only the number from id value changes you can get it by using
var id = parseInt($(this).attr('id').substring(10));
'editResume1'.substring(6) is actually 'sume1'

You can use slice method also to get the digit if the number is always present at the end
var id = parseInt($(this).attr('id').slice(-1));
JsFiddle

You probably need 10 instead of 6 in substring(indexA[, indexB]) also you can give end index
Live Demo
var id = parseInt($(this).attr('id').substring(10));

Related

Finding a span where the class contains a text string JQuery

I am using JQuery to find a span element that contains a string of text in the class, but could also contain other text.
var not_breaks = element.filter("span.this_text");
This works for spans where class="this_text" but not class="this_text_and_more_text" - I need to search for both.
In that case you could use the Attribute Contains selector:
var not_breaks = element.filter("span[class*='this_text']");
You could also use the Attribute Starts With selector, but note that this is only guaranteed to work if the element has a single class on it:
var not_breaks = element.filter("span[class^='this_text']");
We can get all the span class with the name by using a hasclass, Will this help you
var pare=$('span');
$( pare ).each(function() {
if($(this).hasClass('httext')){
alert($(this).html())
}
});
I need to search for both
I'd do that with a selector group:
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
// first ---^ comma ---^ ^---- second
That will retain elements matching either selector in the group.
Example:
var element = $("span");
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
not_breaks.css("color", "green");
<div><span>Not a match</span></div>
<div><span class="this_text">this_text</span></div>
<div><span>Not a match</span></div>
<div><span class="this_text_and_more_text">this_text_and_more_text</span></div>
<div><span>Not a match</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use regex to retrieve the any sequence as you need.
var regex = new RegExp("this_txt");
var elem = $("span").filter(function () {
return regex.test($(this).attr('class'));
});
console.log(elem.length);
regex.test function will only return true if the sequence exists.
here's the fiddle
https://jsfiddle.net/yt1cr2zb/

Generate number on click then pass that to another function

Say I have some text and a button:
<p id="text-box">placeholder text</p>
<button id="text-btn">New Quote Please.</button>
When I click the button I want something new to appear in the #text-box. So I create an array and some jQuery functions:
var textArr = [word0, word1, word2, word3, word4...];
$(document).ready(function() {
$( "#text-btn" ).click(function(){
x = Math.floor(Math.random()*textArr.length); //This line is the problem.
});
$("#text-box").html(textArr[x]);
});
The idea is when the button is clicked a random number is generated then that number is used to select an item in textArr to display in #text-box. I am fairly certain that the problem lays in the commented line. I think that the x value in the $("#text-btn") function is either not being created at all or is not being passed into the $("#text-box") function.
Thank you for your time.
Show us console try console.log . and text-box html must be inside click event.
$(document).ready(function() {
$( "#text-btn" ).click(function(){
x = Math.floor(Math.random()*quoteArr.length); //This line is the problem.
console.log('check', Math.floor(Math.random()*quoteArr.length))
$("#text-box").html(textArr[x]);
});
});
You have some minor mistakes
Try this...
$(document).ready(function() {
var textArr = ['word0', 'word1', 'word2', 'word3',' word4'];
$( "#text-btn" ).click(function(){
var x = Math.floor(Math.random()*(textArr.length));
$("#text-box").text(textArr[x]);
});
});
DEMO
Update
Some mistakes I found is:
you put the $("#text-box").text(textArr[x]); out side the click function
missing bracket x = Math.floor(Math.random()*textArr.length);, correct format is var x = Math.floor(Math.random()*(textArr.length));
Array elements should have quotes (since it is strings).
define array inside document.ready function.
okay, what's quoteArr? you're referencing the wrong array name! try this.
x = Math.floor(Math.random()*(textArr.length));

How to find td element id with value x?

I need to find exactly that td row which contains value priview '2'
I know the td row first half id, but it is dynamic: MovementNumber_M_* (Where * can be from 1 to Milion)
So need to search all rows from MovementNumber_M_1 to MovementNumber_M_9999 which contains MovementNumber_M_*.value=2 and returning directly that td row id which contained that value.
Can you help me? Thanks in advice.
Right and helpfull answers guaranteed ;)
//EDIT
function DgIdOnClick (e,r){
var MovementNumber = document.getElementById(e).value;
//alert('MovementNumber: '+MovementNumber+' Type :'+r);
var result = $('[id^="MovementNumber_M_"][value='+MovementNumber+']');
result.each(function(){
alert($(this).attr("id"));
});
}
OK value=1 is for init and thats why are alerting all rows but if value is 2 then jq is not finding him WHY ?
The function DgIdOnClick is inicialized #
$( document ).ready(function() {
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
var eventH2=SpanBlock2.attr( "onclick" );
SpanBlock2.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(12)).id,2);"+eventH2);
var FirstDiagnosis=$( "span[id^='lov_DgId_D_']" );
var SpanBlock=FirstDiagnosis.find('a');
var eventH=SpanBlock.attr( "onclick" );
SpanBlock.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(11)).id,1);"+eventH);
});
function DgIdOnClick is on other .js file
If i am alerting IN DgIdOnClick alert(document.getElementById('MovementNumber_M_2').value)//MovementNumber_M_2 Then value is 2 but jq is not founding it
This alerts the ID's of each row containing that value
var result = $('[id^="MovementNumber_M_"][value="2"]');
result.each(function(){
alert($(this).attr("id"));
});
http://jsfiddle.net/q8QaG/
Update:
This alerts the id of all inputs with the value of 2, even on input update
$("#button").click(function(){
$('[id^="MovementNumber_M_"]').each(function(){
var value = $(this).val();
if(value == 2){
alert($(this).attr("id"));
}
});
});
http://jsfiddle.net/q8QaG/3/
$('#TableID').find('td').filter(':contains("SOME_TEXT")');
The previous 2 answers have the string encoding similarly incorrect. This should be it:
$('[id^="MovementNumber_M_"][value="2"]');
You can use combination of Attribute Starts With Selector [name^="value"] and Attribute Equals Selector [name="value"]
var myElement= $("[id^='MovementNumber_M_'][value=2]");
As per comment, if you need id use attr()
var myElementId = $("[id^='MovementNumber_M_'][value=2]").attr('id');

how to get the value of an attribute using jquery

I need to get the attributes values of an element.
My code is as follows:
var vid=$('div.selected a');
var dataid=$(vid).data('vid');
var dataalid=$(vid).data('alid');
And HTML
<div class="vblock" id="selected">
<a class="video" data-alid="4" data-vid="4" href="resources/videos/xyz4.mp4">
I need to get the value of data-alid and data-vid of <a> tag. Please anyone help me....
You are almost there with what you have, but you've made a simple mistake. Your markup shows that the div has an ID of "selected", not a class, so you need to use an ID selector:
var vid=$('#selected a');
Notice that I've removed the div from the selector. That's because ID values must be unique within a document and there is therefore no need to qualify them.
Also, note that since $ will return a jQuery object, there is no need to pass vid to it again, which will be slower:
var dataid = vid.data('vid');
var dataalid = vid.data('alid');
trythis
var vid=$('div#selected a');
var dataid=$(vid).attr('data-vid');
var dataalid=$(vid).attr('data-alid');
you have a wrong selector for id.. and you don't need double $(...)
try this
var vid=$('div#selected a');
--------------^--- here this is id and not class
var dataid=vid.data('vid');
-----------^-- here
var dataalid=vid.data('alid');
Try this way, instead of '.' you have to use '#' because you are referring to an id and use .attr() to refer to your specific attribute
$(document).ready(function() {
var vid=$('div#selected a');
var dataalid = vid.attr('data-alid');
var datavid = vid.attr('data-vid');
});

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

Categories

Resources