I need to add the class error to a <label> with the name attribute set to choice_16_0. The code I wrote to do this, however, changes every label on the page to <label for="choice_16_0" class="error">, instead of just adding the new class to the label that already contains for="choice_16_0".
Here's my code:
if (!$("input[#name=\"choice_16_0\"]:checked").val()) {
$("label").attr("for","choice_16_0").addClass("error");
};
What's wrong with this, and how can I fix it?
You selector $("label") is what's selecting every label on the page, change it to $("label[name=choice_16_0") to have it select the single label with the name you want.
var field = $("input[#name=\"choice_16_0\"]:checked");
if (!$(field).val()) {
$(field).attr("for","choice_16_0").addClass("error");
error = true;
};
In jQuery, .attr(attribute, value) is a setter while .attr(atribute) is a getter. You should use selectors instead: $("label[for=choice_16_0]").addClass("error")
Related
I want to be able to change multiple text inputs (but not all) by class, but can't seem to get it working.
Any ideas?
Basically I have multiple reset buttons on the same page I'd like to have 'resetting' the value of the targeted text inputs to nothing.
Here's the code:
$(".reset").on('click', function() {
document.getElementsByClassName('input-1').value = '';
});
It works fine when using getElementById, but I would rather minimise the code and not have to repeat it each time for every text input.
You are already using jQuery, so just use
$(".reset").on('click', function() {
$('.input-1').val('');
});
Notice the . before the class name, same as in .reset.
If you want to use vanilla JavaScript, you have to loop through the HTMLCollection returned by getElementsByClassName:
$(".reset").on('click', function() {
Array.from(document.getElementsByClassName('input-1')).forEach(el => el.value = '');
});
jQuery does that automatically for you.
You can use an special selector for this job:
let inputs = [... document.querySelectorAll("[class^='input-']")];
inputs.forEach(i => i.value = "");
class^= will return all the elements containing class attribute starting with "input".
I have a list of images that each are tied to a class.
var hoverList = this.hoverable.getAllList() //this gets the list.
on mouseover of the images, I want a block of text in a different area, but shares a class, to display. I call
hoverList.mouseover(this.hoverable.displayTheDeets)
and it runs
displayTheDeets: function(){
big=$(".project-details")
thisClass=$(this).attr("class")
console.log(thisClass)
//$(big).find(thisClass).css("display","")
$(big).find(thisClass).css("display", "block")
//$(big > thisClass).css("display","block")
}
From the console, if I run the literal command
$(".project-details").find(".code-fusion")
it returns the element I want. And I can change the display with no problem.
I think my problem is with thisClass. Any thoughts would be appreciated.
Try,
big.find('.' + thisClass).css("display", "block");
or simply
big.find('.' + thisClass).show();
Please note that .attr('class') would return the class being used for the particular element, and it wont return the class name in the format of selector.
Additional Note: And in sometimes if you have more than one class set with that particular element then it would make the selector as invalid like $('.class1 class2 class3')
Try with prefix dot. the attr("class") returns only the name not the prefix dot.
$(big).find("."+ thisClass).css("display", "block")
or
$(big).find("."+ thisClass).show();
Try
$(big).find("."+ thisClass).css("display", "block")
Part of the problem has already been answered well enough; however, I would suggest that you solve this problem in another way.
You can define the class name separately from the class of your hovering element, e.g.
<... class="something" data-linked="theclass">
Then:
displayTheDeets: function(){
var className = $(this).data('linked');
$(".project-details").find('.' + className).show();
}
I have the following code,
HTML
<label for="fName">First Name<sup>*</sup></label>
<input type="text" autocomplete="off" name="fName" id="fName" value='' required/>
JavaScript
var fName = document.getElementById("fName");
fName.label.style.color="red";
Is this a valid way to change the color or the label or does it need it's own id?
Thanks for the help!
Clarification, the color needs to change if the field is empty on the form submit.
Your code is valid for changing attribute color. But I don't think your code will change colour of your label. If this style unique for that element you can use a id for label and make same kind script to change color for label too. I think it would be great if you define a class in css and add this class name using JavaScript,Code for that follows.
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
If your can use jQuery framework. It will save lots of time.
Check out this very complete answer:
Javascript change color of text and background to input value
I believe that there is not any short and direct way to access the attached label corresponding to an input field using javascript. You can access the attached label via CSS (with some tweaks in layout) but in javascript, you have to set up a few lines of code. To use this code, the layout also has a requirement that all the attached label should go before the input field (spaces in between are allowed). This code just use the previousSibling property of a DOM element with some other DOM stuffs. Here is the detail:
function getLabelFromInputID(inputID){
var prevSib = document.getElementById(inputID).previousSibling;
//remove the spaces if any exists
while(prevSib.nodeName=='#text') prevSib=prevSib.previousSibling;
if(prevSib.getAttribute('for') != inputID) prevSib = null;
return prevSib;
}
Use the getLabelFromInputID function to access the attached label from the corresponding input field's ID. Note that the label should have for attribute set-up correctly (this is the standard and common practice).
Here is the Fiddle Demo. In this demo, you just try clicking on the page to see it in action.
This all depends on your use case. If you are simply trying to style the element red statically, you should define a css class (e.g. `red-label { color: red; }) and apply that class to the label.
If you are trying to dynamically set the color to red (e.g. upon a form validation error), you'll need to target the label using a query selector of some sort.
function makeLabelRedDirectly() {
document.getElementById('fNameLabel').style.color = 'red';
}
function makeLabelRedViaClass() {
// Note you can use the more robust `element.classList` with modern browsers
// document.getElementById('fNameLabel').classList.add('red-label');
document.getElementById('fNameLabel').className += ' red-label' ;
}
The examples above use document.getElementById to target the element. You could also opt to use document.querySelector or a library like jQuery to target the labels.
Working example: http://jsbin.com/calol/1
using css
form label{color:red};
using javascript
<label for="fName" class="lbl">First Name<sup>*</sup></label>
<input type="text" autocomplete="off" name="fName" id="fName" value='' required/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js></script>
<script>
$(document).ready(function() {
$('.lbl').css('color','red');
});
</script>
or simple javascript
document.getElementsByClassName("lbl").style.color="red";
An input element does not have a label property or another way to directly refer to its label. You need to assign an id to the label element or otherwise find a way to access it. You could traverse all label elements on a page and use the one with a for property matching the input element, but it’s probably easier to just use id for it.
I am writing a Greasemonkey script and I need to be able to take the value from a hidden form element and set it to a variable.
The hidden form value looks like this:
<input type="hidden" name="ASIN" value="B009MO89Y4" />
I have no ID, class, or any way I can see to set the "value" to a variable. This needs to work dynamically and I currently have no way to establish a class or ID to this value.
Is there a Javascript (or jQuery) method to set this?
In other words:
Find "input" with name "ASIN" and set .val() to a variable?
This selector and assignment:
$("input[name='ASIN']").val(); <---- returns value of that input
var inputVal = $("input[name='ASIN']").val(); <-- Assigns it
var temp = "Stuff";
$("input[name='ASIN']").val(temp); <----Assigns the value of the temp var.
You can use the jQuery attribute equals selector
$('input[name="ASIN"]').val(foo);
You can select it via. name in jQuery like so:
var bar = "Example"; // Example text, to be used in val().
var x = $('input[name="ASIN"]').val(bar);
// Sets the variable x to be the value bar for the input with the name ASIN.
Here's a working jQuery jsFiddle.
In pure Javascript *:
var bar = "Example";
document.getElementsByName("ASIN")[0].value = bar;
Here's a working Javascript jsFiddle.
*Please note that although document.getElementsByName is supported well in Firefox, Chrome and Safari, it has limited browser support. in IE and Opera.
Like this:
$('input[name="ASIN"]').val();
Var:
var hiddenAsin = $('input[name="ASIN"]').val();
You can filter your selection with any attribute.
$('input[name=ASIN]').val("New Value")
You can use selector that targets inputs of type hidden. It should look like that:
$('input[type=hidden]');
or simpler:
$(':hidden');
Use this method
var inputs = document.getElementsByTagName('input');
for(var i = 0...)
{
//go through each input and look for the name "ANSI" and the type is hidden.
//and do your changes.
}
this is for javascript remember.
with this you should be able to get that specific hidden form without an ID nor a Class assigned to that specific form.
For pure javascript:
Try document.getElementsByName('name').
Note that cmptrgeekken pointed out that this has limited browser-support (although that would not be an issue with greasemonkey in FF).
As an alternative, if that hidden element has a fixed place you could also access it by index-number in a predictable collection that you got from knownParent.getElementsByTagName('tag')[#] (So the first hidden inputtag inside a form would be number 0).
Another variation is to get (again) knownParent.getElementsByTagName('tag') and loop over that collection to see what element has the 'name' attribute set that you seek.
Simply do:
var target=knownParent.getElementsByTagName('input'), L=target.length;
while(L--){ if(target[L].name==='name'){target=target[L]; break;} }
alert(target.value); //target is now the element you seek.
Example fiddle here.
Good luck!
I'm trying to figure out how to set the input value of a text field to the value of it's title when the page loads, as a way to show placeholder text. I'm using an HTML4 Strict doctype. I don't want to store the placeholder text in the input value, because I don't want people without javascript to have to delete the text before typing. I want it to be added with javascript, and then removed when the input gains focus. I have the focus() and blur() methods working, but I can't figure out how to write the initial pageload function to pass the input's title to the val() function.
I currently have this code:
// This doesn't work, it grabs the page title:
$('#item-search').val(this.title);
// Works:
$('#item-search').focus(function() {
if (this.value == this.title) {
this.value = '';
}
});
// Works:
$('#item-search').blur(function() {
if (this.value == '') {
this.value = this.title;
}
});
Just to add another variation, .val() can accept a function as its parameter, fixing your this issues:
$('#item-search').val(function () {
return this.title;
});
this refers to the current scope. In your first example, its referring to document.
You may want.
$('#item-search').val($('#item-search').attr('title'));
Even better:
var $itemSearch = $('#item-search');
$itemSearch.val($itemSearch.attr('title'));
$('#item-search').val(this.title);
In this line this refer the document(html) and set the <title>. To accomplish you job do this:
$('#item-search').val($('#item-search').attr('title'));
Try this:
$('#item-search').val($('#item-search').attr('title'));
Please try this.
$('#item-search').val($("#item-search").attr("title"));