<label class="checkbox-1">
<input class="checkbox" type="checkbox" name="" value=""> Add
</label>
How to change the text "Add", with java script? Note: I don't want to delete the checkbox, only to change the text.
add id attr to the html and use the following JavaScript code:
var selector = document.getElementById('someText');
selector.lastChild.textContent = 'hiiiiiiiii';
<label id="someText" class="checkbox-1">
<input class="checkbox" type="checkbox" name="" value="" > Add
</label>
Depends on whether you want to do this in native javascript or another external library; like JQuery. Assuming native javascript, it can be done like so:
document.getElementById("checkbox1").textContent= "<modifiedtext>" ;
<label class="checkbox-1">
<input class="checkbox" id="checkbox1" type="checkbox" name="" value=""> Add
</label>
Notice the new id to make searching and variablising the dom element easier. Ideally DOM manipulation is better done in JQuery. At least from my experience.
The previous answer that I contributed did not target the main problem. So because the label text exists as a parent of the input we need to go through another way.
I have posted a snippet using JQuery.
// find elements
var checkbox = $("#checkbox1")
var labelCheckbox = $("#checkbox1").parent('label')
$( document ).ready(function() {
console.log( "ready!" );
checkbox.text('New')
labelCheckbox.text('Hello')
});**strong text**
Once the document is loaded, it will change the text by finding the parent element of the input type which we assume is the label and then change the text.
Related
<span>
<input name="" autocomplete="off" label="" class="form-control mandatory field-mandatory" placeholder="">
<span class="goog-combobox-button"/>
<input type="hidden" value="3" id="ctl00_cntMainBody_OBJECT_ONE__PMLookupField" name="ctl00_cntMainBody_OBJECT_ONE__PMLookupField">
</span>
I would like to find out if there is a way, using jQuery, to find if the input above the one with id=ctl00_cntMainBody_OBJECT_ONE__PMLookupField has a css class field-mandatory. There are many spans on the page with similar to this one. I am working within the existing structure of html with no option to change. Since the input has no id the only way to locate it is by using the input below it that has an id.
Find each hidden input and target the sibling you want :-
$("input[type='hidden']").each(function() {
var inputAbove = $(this).siblings('input.field-mandatory');
// DO SOMETHING
});
I have an input field like below
<input class="d_o" type="radio" value="super" name="old_or_new" checked="checked"> Get this value actually</input><br/>
I have to get the value of the input field i.e., Get this value actually, so tried the below jquery code
console.log($('.d_o').text());
But i am surprised that its returning nothing, and its working when tried to get the value like $('.d_o').val()
So how to get the text value from the above input field using jquery am i missing anything ?
The entirety of your <input> element is
<input class="d_o" type="radio" value="super" name="old_or_new" checked="checked">
The text that's after it, and the invalid html </input> are completely different nodes in the DOM tree. So val returns the value "super" as expected, but there's no text for text to return.
The .text() method cannot be used on form inputs or scripts
http://api.jquery.com/text/
Although I am not sure what approach jQuery follows on this : One explanation can be the "Content Model" specification of each HTMLElement .
Content model
A normative description of what content must be included as children and descendants of the element.
For example :
For Input type : http://www.w3.org/TR/html5/forms.html#the-input-element
Content model:Empty.
However for Title Element this is defined as
Content model : Text
http://www.w3.org/TR/html5/document-metadata.html#the-title-element
Eager to see the validations on this postulate :)
<input class="d_o" type="radio" value="super" name="old_or_new" checked="checked"> Get this value actually</input><br/>
This is not the correct way to handle the <input> tag. You should use :checked and .val() instead:
$(document).ready(function(){
$('#hey').on('click', function(event){
alert($('.check:checked').val());
});
});
<h2>Select old or new</h2><br>
<b>Old</b>:<br>
<input type="radio" class="check" name="old_or_new" value="old"><br>
<br>
<b>New</b>:<br>
<input type="radio" class="check" name="old_or_new" value="new"><br>
<br>
<input type="button" id="hey">
Check the fiddle: http://jsfiddle.net/MLWCK/
I have a list of checkboxes that go together. One is for a name the other is for a price. I need to check the one for price and the corresponding name one gets automatically checked.
Here is my code:
<input id="name1" name="name1" value="Option Name 1" type="checkbox">
<input id="price1" name="price1" value="125" type="checkbox">Option Name 1<br>
<input id="name2" name="name2" value="Option Name 2" type="checkbox">
<input id="price2" name="price2" value="150" type="checkbox">Option Name 2<br>
<input id="name3" name="name3" value="Option Name 3" type="checkbox">
<input id="price3" name="price3" value="175" type="checkbox">Option Name 3<br>
How can I do this with javascript? I could do it if it were only one set, but I don't know how I would do this without making a separate function for each one. This list of check boxes is created dynamical with PHP, so there will be more or less depending on the item in the database that is selected.
probably something like this?
Add class name and price for the checkboxes for easy detection. And using event deleagtion since you are dynamically appending the
$(document).on('change','.name, .price', function () { //provide a container selector instead of document.
$(this).next('br').prevAll(':eq(1),:eq(0)').prop('checked', this.checked);
});
Fiddle
if you dont want to add another class to the markup then use startswith selector, and for both way toggle.
$(document).on('change',':checkbox[id^=name],:checkbox[id^=price]', function () { //provide a container selector instead of document.
$(this).nextUntil('br').andSelf().prev().andSelf().prop('checked', this.checked);
});
Fiddle
This just select the next available br
Give the price inputs a class of "price" or something similar, and give the name inputs a class of "name" or somthing similar.
Then bind the events using the class selector, and find the corresponding checkbox using next('.price') or previous('.name')
I'd add a class to each input and it's easy from there:
$(document).ready(function() {
$(".name").change(function(){
if($(this).is(":checked")){
$(this).next().attr("checked","checked");
}else{
$(this).next().removeAttr("checked");
}
})
});
checkout jsfiddle: http://jsfiddle.net/megarameno/BSYvE/
Don't use <br> anymore, instead, wrap them in divs. That way they can be recognized as a DOM group and your JS can be intelligent - no need for a bunch of event handlers!
This example uses jQuery: http://jsfiddle.net/Nu8w9/2/. It checks the whole row either way, which I think is what you want. Interpreting your question literally, it would just be $('.row').on('change input:nth-child(2)', function (e) { $(e.target).closest('.row').find('input:nth-child(1)')[0].checked = e.target.checked; });
I have some code that's finding the 'title' attribute from each child in a form.
It pulls out the title just correctly when I run 'console.log('title'). But when i try to apply the code to insert a label before the inner div of the fieldset, it just adds the same title ('About Me') to each of them.
html
<form action="#" method="post">
<fieldset title="About Me">
<!-- Going to convert legends to h4 // can choose the header style element? -->
<div>
<label for="name">Text Input:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
</fieldset>
<fieldset title="Radio Button Choice">
<div>
<label for="radio-choice-1">Choice 1</label>
<input type="radio" name="radio-choice-1" id="radio-choice-1" tabindex="2" value="choice-1" />
<label for="radio-choice-2">Choice 2</label>
<input type="radio" name="radio-choice-2" id="radio-choice-2" tabindex="3" value="choice-2" />
</div>
</fieldset>
<fieldset>
<div>
<label for="select-choice">Select Dropdown Choice:</label>
<select name="select-choice" id="select-choice">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
</fieldset>
</form>
jQ
kids = this.element.children('fieldset');
kids.each(function(){ //function to do something to each of the child fieldset elements
console.log(this);
title = $(this).attr('title');
console.log(title); //this logs each title fine, or 'undefined' where there isn't one
$("<legend>" + title + "</legend>").insertBefore('div:first-child')
//that's where I'm just getting 'About me', on every damn one....
});
Can anyone spot where I'm being a fool? Thanks.
Your selector is too generic - div:first-child will select all of the divs. Look for the div that is a descendant of this fieldset.
// Based on your existing code
$("<legend>" + title + "</legend>").insertBefore($(this).find('div:first-child'));
// Slightly cleaner
$(this).prepend("<legend>" + title + "</legend>")
Also, make sure you make title a local variable with the var keyword:
var title = $(this).attr('title');
Dennis beat me to it, anyhow here's working example with slightly different approach to selecting first child http://jsfiddle.net/gMb8m/1/
The problem was that you were using wrong selector.
EDIT:
To address some of OP questions.
As to using .children(0) instead of .find('div:first-child') - I would have to check with jQuery source, but I imagine using the later may be slower since it using involves parsing selector while the .children(0) probably uses native DOM .childNodes internally. Passing a 0 to it just returns first child.
One situation in which using .find('div:fist-child') would be better if on some pages fieldset first child wouldn't be a div element and you would still want to insert legend before first div NOT before the first child. In that case using .find would return the first div.
As to why using prepend over insertBefore - they're both good (as you can tell from Dennis answer) and can be used in your situtation. It's just a matter of choice how you write your selectors. In this case I find my way cleaner.
P.S. In the example I've replaced your kids with my selector for fieldsets - don't mind that.
.prepend() seems to do what you're going for:
$('fieldset').each(function() {
$(this).find('div:first-child').prepend('<legend>' + this.title + '</legend>');
});
Also, there's no need to promote a DOM object to a jQuery object as just to access a DOM attribute as in $(this).attr('title') :)
Short Question:
How do you link a label element to an input element without using the input element's id using jQuery and javascript?
Long Question:
I am using jQuery to clone a form with possibly more than one instance of the form being available for the user to fill in.
A label's 'for' attribute is supposed to be set to the 'id' attribute of the input element that it is for. This works when the input element has a unique id.
Because I am cloning the same input element there will be multiple input elements with the same id in the document. Therefore I'm avoiding having id attributes for input elements but I'd still like to focus on the input element when the label is clicked. I also want to avoid generating random ids for fields or setting onclick events on labels.
Edit #1
Example mark up (note no ids)
<form>
<label>First Name:</label><input type='text' name='FirstName' /><br/>
<label>Last Name:</label><input type='text' name='LastName' /><br/>
</form>
Example cloning code:
var newForm = $('form').clone();
$(newForm).find('label').each(function(){
var inputElement = $(this).next('input');
// I'd love to set the label's for attribute to an element
$(this).attr('for', inputElement);
});
$(document).append(newForm);
Edit #2
There currently are three options:
Set onclick events for labels to focus on the input field they're for. Criteria for deciding which labels are for which inputs can be the next input element or something else
Embed the input fields in the label fields (might not be possible due to designer's choices)
Generate random ids while cloning each form
Well it would be nice to see the markup, but if i can assume that the markup will look somewhat like this
<form name="f1">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
<form name="f2">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
then you could do something like this
$('form label').live('click',function(){
$(this).next('input').focus();
});
you will need to use live or delegate since you're cloning the forms on the fly i'm assuming.
The simplest solution is to move the <input> tags inside the <label> tags and forgo the for attribute altogether. Per the HTML spec, <input> tags without for attributes are implicitly associated with their contents.
Try this:
<form>
<label>First Name: <input type='text' name='FirstName' /></label><br/>
<label>Last Name: <input type='text' name='LastName' /></label><br/>
</form>
(See: http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1)
You shouldn't have multiple identical ids in the page. It defeats the purpose of the id attribute and is against the W3C spec.
Regardless, jQuery's $(this) could help you in this situation. Say you gave all your the "focusable" class. Then you could do:
$('.focusable').focus( function(){
$(this).doSomething();
});
This is really an HTML question. A label can be associated wtih a form control either by its for attribute having the same value as the associated control's id attribute, or by having the control as a child of the label, e.g.
<form ...>
<label for="nameField">Name:<input id="nameField" name="nameField" ... ></label>
<label>email:<input name="emailField" ... ></label>
</form>
I suppose in jQuery you need something like:
var labelAndInput = $('<label>text<input ... ></label>');
or whatever. Note that older versions of IE (and maybe more recent ones too) the label will not be associated with the control without the for attribute (or htmlFor property), there is no other way.