Jquery - Create dynamic name selector - javascript

I have been playing with this for the last hour, but just cant get it to work.
I have a reactJS component, that renders a grid. After the grid is rendered I need to do some DOM work on the component.
There are some checkboxes that need to be checked. After the DOM is available if I run this in console:
$('[name="checkbox0"]').prop('checked', true);
It works great.
I need to iterate my objects, and based on condition check it or not.
My question is how to make the selector dynamic? How do I make checkbox0 dynamic, so I can set it to checkbox1, checkbox5... etc.
This is my latest attempt to solve the issue, and it did not work:
this.state.rows.forEach(function (index, key, value){
var test = "'[name=" + "checkbox" + key + "]'" ;
if(index.selected){
//$('[name="checkbox0"]').prop('checked', true);
$(test).prop('checked', true);
}
});

You are trying to use an attribute selector, but the syntax is way off in the dynamic string
var test = '[name="checkbox' + key + '"]'
You are wrapping the entire string with a "" where it should have only for the attribute value

Related

How do I access elements in jquery if the id is based on one of the function arguments?

I am trying to access an element in jquery using a function input. To clarify, here is an example of what I have tried that isn't working:
function openReceivedMessage(messageid)
{
// ajax post query that is executing fine
// set row to not be highlighted
var rowid = 'receivedrow' + messageid.toString();
document.getElementById(rowid).style.background-color = "#ffffff";
// other code that is executing fine
}
Essentially, this is for a message inbox page. I have displayed the messages in a table, and, as the number of messages changes for each user, I used a loop to populate it. In order to open a message, I have hoped to use a jquery function (titled above), and so when the loop populated the tables, I set it so that each of the different subject lines would, onclick, execute the above function with the unique messageid passed in as the argument. Upon opening, I want to change other things in the table (that I named, similar to the message function, as things like 'receivedrow#' where # is the messageid.
Would hugely appreciate any help here, I feel like there must be a simple way create a string (like I did with rowid above) and access the element with that id (in the table there is a row with id="receivedrow#" that I want to adjust the css of).
I recommend using jQuery to find the element
var rowid = 'receivedrow' + messageid.toString();
var $el = $("#" + rowid);
Then simply operate on $el
$el.css({'background-color':'#FFFFFF'});
If you're having trouble still, I recommend checking that rowid is correct and that the jQuery is then giving you the right element back.
function openReceivedMessage(messageid)
{
var rowid = 'receivedrow' + messageid.toString();
var $el = $('#'+rowid);
$el.css({'background-color':'#FFFFFF'});
// other code that is executing fine
}
Seems what you have posted is not jQuery at all :D
It is simple JavaScript trying to get a DOM element with id rowid. It does not works maybe be because of following two reasons:
there is no element with id rowid which you can easily verify.
background-color is not a property its backgroundColor.
Try using this:
document.getElementById(rowid).style.backgroundColor = "#ffffff";
If you what you really need is an easy way get the id onclick, then simply use the this keyword in your row markup.
onclick="openReceivedMessage(this);"
Then access in your function as such:
function openReceivedMessage(row)
{
// set row to not be highlighted
var rowid = 'receivedrow' + row.id;
$('#' + rowid).css({'background-color':'#ffffff'});
}

How can I update the background color of a dynamic input control?

I'm successfully creating some dynamic input textboxes using the following javascript:
var type = "Textbox";
var foo = document.getElementById("fooBar");
for (i = 1; i <= totalQty; i = i + 1) {
var textbox = document.createElement("input");
//Assign different attributes to the element.
textbox.setAttribute("type", type + i);
//textbox.setAttribute("value", type + i);
textbox.setAttribute("name", type + i);
textbox.setAttribute("id", type + i);
textbox.setAttribute("style", "width:300px");
textbox.setAttribute("width", "300px");
//Append the element in page (in span).
var newline = document.createElement("br");
foo.appendChild(newline);
foo.appendChild(textbox);
}
Everything works fine with that. Once the user keys in data and clicks submit however, I need to go back and set the background-color of any textboxes with an error to red. I found some code to do the actual coloring:
textbox.style.backgroundColor = "#fa6767";
...and I know the exact name of the textbox with the error (i.e. "Textbox1", "Textbox2", "Textbox3", etc) but I'm not sure how to programatically assign this background color code to the specific textbox. I can't use something like this, since all code is dynamically generated:
errorTextbox = $("#Textbox1");
Any suggestions?
It looks like you're building a form validation script. Here's an easier way to do this:
1) Create an entry in your stlyesheet for your error class. Adding and removing a class requires fewer steps than assigning properties individually.
.error {
background-color: #ff0000;
}
2) Give all the textboxes you wish to validate a unique class name "valMe", for example.
3) Then loop through them during the validation step:
$('.valMe').each(function() {
$(this).removeClass('error');
if($(this).text=='') {
$(this).addClass('error');
}
})
By using "this" you refer to the current element, so you don't even need to know the ID of the element.
If you already know the name (in this case identical to the id) of the element, you can use jQuery to select the element by forming the selector using string concatenation. Assuming you have a variable that stores the name/id of the text box that has the error, then it's a relatively simple process:
var errorTextboxName = 'Textbox1';
$('#' + errorTextboxName).css('background-color', 'red');
I ended up going with the following:
document.getElementById('Textbox1'.style.backgroundColor = "#fa6767";
I originally didn't think I would be able to capture my "Textbox1" control in this fashion since when I viewed the html source code, there was no "Textbox1" due to the fact I dynamically created it.
Thanks.

Need to select a drop down list element with a particular attribute value from a list of drop down lists and set its selected value

.FilterList is the class name of all the drop down lists
var $lists = $('.FilterList[ctype="' + ctype + '"]').css('display', 'inline');
Something like the below works fine but I was wondering if there's a more concise and efficient method
I could use instead of the .each()
$lists.each(function () { $(this).attr('filterid') == filterid ? $(this).val(thisval) : null; });
Whilst I am after something more like:
$lists.first('.FilterList[filterid = "' + filterid + '"]').val(thisval);
Your question is a little vague without any HTML to demonstrate what you're trying to grab from the DOM, but from what I gather, it seems like something like this should work:
$lists.find("[filterid='" + filterId + "']").val(myVal);
Honestly, though, I'm just guessing at what it is you are looking for. Try creating a jsFiddle to give us a better idea of what you're after.

Problem disabling/enabling multiple form elements using javascript

I'm trying to disable/enable multiple form elements of an HTML page using javascript. I have a form with many fields, each row of the form has a checkbox to enable/disable the elements on the row.
The problem is, only the first two form elements get disabled (no matter the order). After that, the remaining javascript code in the function just won't be executed anymore.
Here's the code (it's part of a function called by the onChange attribute of every checkbox):
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_quantity")[0].disabled = !theBox.checked;
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_description")[0].disabled = !theBox.checked;
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_price")[0].disabled = !theBox.checked;
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_language")[0].disabled = !theBox.checked;
Each form element has a different (and unique) name, and the single lines of code work just fine... until you put them together.
For example: in the above code, "quantity" and "description" fields will get disabled/enabled, but "price" and "language" won't.
If i change the order of the lines, the first two get always executed, no matter what.
Then every line of code doesn't work; it's like it's commented. I even put some alerts to try debugging, but they just get ignored (no dialog shows up at all) if I insert them after the above code. The elements names are correct.
I'm sure I've made a mistake somewhere, but since the single lines of code are working, I don't know where to look... it's driving me nuts!
Please, I could really use some help.
I just made it work and, as I thought, it was a very bad mistake.
The problem was, not every form row in the HTML has all of those 4 fields. So, basically, I was trying to access a property of a null object.
I solved it by putting:
if( document.getElementById(id) != null )
before trying to manipulate the element.
Sometimes when you're in a hurry, you end up neglecting some very basic stuff...
Thank you for your time.

How to set the value for form fields

I want save multiple individual records for a single model. So my form will have <input> elements with IDs that look like this Author0Title; Author1Title; Author2Title, etc.
I will be getting values for these input's using jQuery.getJSON() method.
I want to assign individual values for these input like these automatically.
document.getElementById('Author0Title').value = respose.data[0].title;
something like..
for(i=0;i<response.data.length; i++){
var id = 'Author' + i + 'Title';
document.getElementById(id).value = respose.data[0].title;
}
But it is not working. I appreciate any help.
Thanks.
If you're using jQuery:
for (var i = 0; i < response.data.length; i++) {
$('#Author' + i + 'Title').val(response.data[i].title);
}
That's pretty close to your example, except that you've got '0' coded in as the index instead of 'i'.
Make sure that your <input> elements really are using both an "id" and a "name" that's constructed as you expect. If they're just getting the "name" attribute set, you could do this:
$('input[name=Author' + i + 'Title]').val(response.data[i].title);
Could it be that you're misspelling respose -> response?
Otherwise, "should work". Assuming your JSON actually matches what you're looking for in this code.
Since you're using jQuery, you might want to use $('#Author' + i + 'Title').val(response.data[i].title); instead - although it does the same.

Categories

Resources