jQuery ID starts with - javascript

I am trying to get all elements with an id starting with some value. Below is my jQuery code. I am trying to use a JavaScript variable when searching for items. But it does not work. What am I missing below? So the id 'value' am searching is the value of the clicked element
$(document).ready(function() {
$('input[name$="_chkmulti"]').click(function(){
var value = $(this).val();
$("td[id^= + value +]").each(function(){
alert("yes");
});
});
});

try:
$("td[id^=" + value + "]")

Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.
Note that the quotes are mandatory: [id^="...."].
Source: http://api.jquery.com/attribute-starts-with-selector/

Related

jquery - find 'label' element by 'for' attribute and reset 'for' attribute to new value

I've searched and have found the following to fetch the label.
var label = $("label").attr("for", id);
my initial attempt was to try a variant:
$('label[for|="'+oldId+'"]').attr('for',newId);
where oldId is the current value and newId is the new value.
I don't get an error, but nothing gets changed.
I also tried just fetching the id of the label so I could find the element by id and change the attribute value, but when I try:
var label = $("label").attr("for", oldId);
var id = label.id;
I get id as undefined.
So, basically I want to:
- find a label element by it's for attribute.
- reset the for attribute to a new value.
The requirement seems a bit odd, but:
So, basically I want to:
find a label element by it's for attribute
var theLabel = $('label[for="' + theValueYouWantToFind + '"]');
reset the for attribute to a new value
theLabel.attr("for", theNewValueYouWantItToHave);
This will associate the label with a different element than it was originally associated with (the one with id matching theNewValueYouWantItToHave).
Live Example This starts out with "click me" connected to the checkbox to the left of it. If you click "switch" it connects it to the checkbox on the right instead:
var currentId = $("label").first().attr("for");
$("input[value=Switch]").on("click", function() {
var newId = currentId === "left" ? "right" : "left";
var label = $('label[for="' + currentId + '"]');
label.attr("for", newId);
currentId = newId;
});
<div>
<input type="checkbox" id="left">
<label for="left">Click me</label>
<input type="checkbox" id="right">
</div>
<input type="button" value="Switch">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can try as below:
DEMO HERE
var oldId="#myId";
$('label[for="'+oldId+'"]').attr('for',"#newId");
Now the explanations:
var label = $("label").attr("for", id);
Here you are trying to assign id value to the variable and at the same time you are trying to change it
$('label[for|="'+oldId+'"]').attr('for',newId);
This line you have a syntax error after for you have added | instead of ]
var label = $("label").attr("for", oldId);
var id = label.id;
Again the same problem - assignment and change which does not do anything and label will not have any value thus giving you undefined error
Documentation for JQuery's attr
Before you go much further, why are you wanting to change the "for" attribute and is it going to be processed again after you change it?
attr with one parameter returns the value of the attribute ie: attr("for"). attr with two parameters sets the value of the attribute id: attr("for", newValue).
$("label").attr("for", id);
sets the attribute "for" to the value of id.
$('label[for|="'+oldId+'"]').attr('for',newId);
Jquery selector test site confirms that your selector is good. From what I'm seeing this is correct as long as oldId is the value you are looking for, the attribute should change to newId.
var label = $("label").attr("for", oldId);
var id = label.id;
This will find all "label" and set their attribute of "for" to oldId.
the setting attr is returning jquery, but without researching it, I would be surprised if it was returning the label rather than the contents of the attribute it is setting to "oldId", so this will most likely not do what you want.

jQuery id does not yield text representation

I’d like to add a button to certain text fields to allow for additional input methods. Since the button should be able to reference the text field it belongs to, I'm adding a parameter to the function call within the button’s onClick() handler, containing the ID of the text field.
At least, this is my plan. When I obtain the ID of the text field, and display it in an alert, it displays nicely. However, when I use the result of $(this).attr('id') as a function parameter, I'd expect a string to be given to the function (the id of the element). Instead some weird object is given.
How do I convert that object to a string? Or is there a conceptual flaw?
<form>
<input class="joeDateTime" type="text" name="n1" id="n1" value="2014-09-01 17:30:00">
</form>
<script>
function handleJoeDateTime(e)
{
alert('Edit '+e); // shows 'Edit [object HTMLInputElement]'
}
$(document).ready(function() {
$('.joeDateTime').each(function(){
var i = $(this).attr('id');
alert(i); // shows 'n1'
$('<button onclick="handleJoeDateTime(' + i + ');return false;">πŸ“…</button>').insertAfter($(this));
});
});
</script>
You are not passing i as a string value, you are passing it as an variable. In modern browsers the element's id are copied to properties of the window object(so you can access then as global variables).
So you need to enclose them using quotes to pass i as a string value
$('<button onclick="handleJoeDateTime(\'' + i + '\');return false;">πŸ“…</button>').insertAfter($(this));
Demo: Fiddle
Also Instead of using inlined event handlers, I would recommend using jQuery event handlres
$('.joeDateTime').each(function () {
var i = $(this).attr('id');
console.log(i); // shows 'n1'
$('<button />', {
text: 'πŸ“…',
click: function () {
handleJoeDateTime(i);
return false;
}
}).insertAfter(this);
});
Demo: Fiddle
Your problem lies here:
$('<button onclick="handleJoeDateTime(' + i + ');return false;">πŸ“…</button>')
where this should be
$('<button onclick=\"handleJoeDateTime(\"' + i + '\");return false;\">πŸ“…</button>')
When you're passing an element to jQuery ( $ ), it becomes a jquery object.
It had been made to handle id, class, elements, not html chunks.
What you want is inserting a piece of concatenated elements as an html node.
so first concatenate your elements then append it with the jQuery's after() method.
(or create/append it with vanilia js var btn = document.createElement("BUTTON");)
var Button = '<button class=\"AltBut\" id=\"' + i + '\">πŸ“…</button>';
$(this).after(Button);
or ( for compacity )
$(this).after('<button class=\"AltBut\" id=\"' + i + '\">πŸ“…</button>');
In this exemple, I'm adding an id to each enabled buttons where I store your variable i
Then add a click listener to those buttons, avoid inline js at all price, for maintainability's sacke.
$('.AltBut').on('click',function(){
var i = $(this).attr("id");
alert("i= "+i);
return false;
})
The whole demo is here: http://jsfiddle.net/x6x4v90y/1/

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');

Html TD back to DOM

the issue: I have an appending json data to html table
here's how:
In a Loop->
var image = document.createElement('img');
image.src = data.data[i].picture.data.url;
var td=document.createElement('td');
var input=document.createElement('input');
input.setAttribute('type', 'checkbox');
input.setAttribute('onclick', 'testCheckBox()');
input.setAttribute('id','testid' + i)
td.setAttribute('onclick','tdClick()')
td.setAttribute('title',data.data[i].name );
td.setAttribute('id',''+ i );
td.appendChild(input);
td.appendChild(image);
tr.appendChild(td) ;
mytable.appendChild(tr);
}
$('#maincontent').append(mytable);
After that I got the data I need in attributes,
now I want to understand how can I get the TD= ID , and any other kind of attributes after that kind of click or another, from each td... that is different
Edit:
Function fixed to this :
function testCheckBox()
{
$(':checkbox').change(function(){
var i = $(this).closest('input').attr('id');
var id = $(this).closest('td').attr('id');
var fbname = $(this).closest('td').attr('title');
console.log(id + ' : ' + this.checked);
console.log(fbname + ' : ' + this.checked);
console.log(i + ' : ' + this.checked);
friend_name[i]=fbname;
friend_id[i]=id;
});
}
console.log(friend_name);
Working just GREAT!
the new Issue is that.. if I uncheck this checkbox.. I dont know how to remove it from Array!
and another Q: can I make 1 Array and not 2 Like here? that the 'I' will have 2 Elements Inside?
You are not javascripting the right question, i mean, you ask for the .html() and not the ID value.
HTML()
Get the HTML contents of the first element in the set of matched
elements or set the HTML contents of every matched element.
Try this :
console.log($(this).attr('id'));
attr()
Get the value of an attribute for the first element in the set of
matched elements or set one or more attributes for every matched
element.

jQuery: Pass variable to :eq() does not work

I have been trying to find out why the following lines of code do not work:
$('#add-cloud > select').change(function() {
var selected = parseInt($('#add-cloud select option:selected').val());
$("#cloud-calculator table tr:eq(selected)").css("color", "red");
});
If I change :eq(selected) to :eq(4) for example - works fine. How do you pass variable as an argument to :eq() ?
You have to concatenate your variable with your selector:
$("tr:eq("+selected+")");
The way you're doing it, you're embedding the actual string "selected" in the selector. You need to construct a string using your selected variable as a part of it:
$("#cloud-calculator table tr:eq(" + selected + ")").css("color", "red");
Also, you can simply use the 'this' object to get the seleted value.
$('#add-cloud > select').change(function()
{
var rowSelector = '#cloud-calculator table tr:eq(' + parseInt(this.val()) + ')';
$(rowSelector).css("color", "red");
}
Yes we can pass variable to eq() function. But you need to disable Firebug. Otherwise it wont work.
Please check this example.
var index = 3
$('#sidebar_menu li:eq('+index+')').css({"color":"#050959"});

Categories

Resources