Change label text with jQuery but not other label elements - javascript

I have 2 radio buttons and each of them inside a label.
<fieldset>
<label><input type="radio" name="invoice_type" value="Receipt"> Receipt</label>
<label><input type="radio" name="invoice_type" value="Invoice"> Invoice</label>
</fieldset>
I tried to change the label text with jQuery with this code but it replaces entire label content, including the radio boxes.
$('fieldset>label:eq(0)').text('Some text');
$('fieldset>label:eq(1)').text('Some text');
how i can replace only the label text without touching the radio boxes?

You should consider rearranging your HTML.
$('fieldset>label:eq(0)').text('Some teqxt');
$('fieldset>label:eq(1)').text('Some text');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<label for="label1">Receipt</label>
<input type="radio" id="label1" name="invoice_type" value="Receipt">
<label for="label2">Invoice</label>
<input type="radio" id="label2" name="invoice_type" value="Invoice">
</fieldset>

To make minimal changes to your layout and still not need an id= and related for=:
add a span to wrap your text and target the span
this also has the added bonus of allowing some styling to be added to the span, eg for consistent spacing
label>input+span { margin-left:0.75em; }
without relying on additional spaces in both the original markup and in the replacement text
$("button").click(() => {
$('fieldset>label:eq(0)>span').text('Some text');
$('fieldset>label:eq(1)>span').text('Some other text');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<label>
<input type="radio" name="invoice_type" value="Receipt">
<span>Receipt</span>
</label>
<label>
<input type="radio" name="invoice_type" value="Invoice">
<span>Invoice</span>
</label>
</fieldset>
<button>click me</button>
Note
https://api.jquery.com/eq-selector/#eq1
As of jQuery 3.4, the :eq pseudo-class is deprecated. Remove it from your selectors and filter the results later using .eq().
left it in above so that it matches OPs code more closest, the alternative would be:
$("fieldset>label").eq(0).find(span)
or target the individual label directly
$("input[value='Receipt']").next()
(based on the current layout)

Using simple vanilla JS this is easy (no clue about jQuery though, stopped using that in 2015), and does not require any changes in the markup:
document.querySelector('fieldset>label').childNodes[1].textContent = ' foo';
document.querySelector('fieldset>label+label').childNodes[1].textContent = ' bar';
<fieldset>
<label><input type="radio" name="invoice_type" value="Receipt"> Receipt</label>
<label><input type="radio" name="invoice_type" value="Invoice"> Invoice</label>
</fieldset>

Here is a solution that does not require to change your HTML and uses jquery:
$('fieldset>label:eq(0)').contents()[1].textContent = 'Some teqxt';
$('fieldset>label:eq(1)').contents()[1].textContent = 'Some text';
If you have multiple tags inside the <label> tag you can use the more correct filtering version:
$('fieldset>label:eq(0)').contents().filter(function () { return this.nodeType === 3; })[0].textContent = 'Some teqxt';
$('fieldset>label:eq(1)').contents().filter(function () { return this.nodeType === 3; })[0].textContent = 'Some text';

Related

How to update Label text that also contains an Input element

I am trying to update just the text within the label, but not touch the input value in any way.
<div id="shippingRates">
<label>
<input type="radio" name="shippingrate" class="shippingratequote" value="GUID1" />
Text I want to Update
</label>
<label>
<input type="radio" name="shippingrate" class="shippingratequote" value="GUID2" />
Random Text
</label>
</div>
Playing around in the console, this Javascript returns just the text of the label:
$('#shippingRates :input[value="GUID1"]').parent().text();
But what is happening is if I execute:
$('#shippingRates :input[value="GUID1"]').parent().text("TEXT UPDATED!");
It overwrites the entire contents of the Label element, including the input element.
How am I able to update just the text using jQuery/javascript?
EDIT: FYI, I am unable to make any changes to the HTML as it comes in from an external server-side function.
Thanks
You can use the DOM to grab the text node following the input:
$('#shippingRates :input[value="GUID1"]')[0].nextSibling.nodeValue= 'TEXT UPDATED!';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="shippingRates">
<label>
<input type="radio" name="shippingrate" class="shippingratequote" value="GUID1" />
Text I want to Update
</label>
<label>
<input type="radio" name="shippingrate" class="shippingratequote" value="GUID2" />
Random Text
</label>
</div>
Another way to do it...
$('#shippingRates :input[value="GUID1"]').parent().contents().filter(function(){
return this.nodeType == 3;
})[1].nodeValue = "The text you want to replace with"

How to get the selected radio button label text using jQuery

I have a radio button like this on page
<div id="someId">
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">Yes</label>
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">No</label>
</div>
On page load I don't want to set any selection so not using checked property. In my JavaScript function, how can I get the value Yes or No based on the user selection at runtime?
function GetSelectedVal() {
console.log($('#someId input:radio.........);
}
I have seen similar questions but unable to find solution of this issue.
Remove onchange inline handler from HTML. Use on to bind events.
:checked will select the checked radio button. closest will select the parent label and text() will get the label associated with the radio button. e.g. Yes
$('[name="x"]').on('change', function () {
alert($('[name="x"]:checked').closest('label').text());
});
DEMO
You can simple pass this in onchange="GetSelectedVal(); like onchange="GetSelectedVal(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId">
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">Yes</label>
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">No</label>
</div>
<script>
function GetSelectedVal(ele) {
alert($(ele).closest('label').text());
}
</script>
I would do it a bit different than the accepted answer.
Instead of having events on multiple radio buttons, you can have one on the containing div. Also let just the checked radio trigger the change:
$('#someId').on('change', 'input[name="x"]:checked', function () {
var label = $(this).siblings('span').text();
console.log(label);
});
When I have text next to other elements I prefer wrapping the text in span's:
<div id="someId">
<label class="radio-inline"><input name="x" type="radio"><span>Yes</span></label>
<label class="radio-inline"><input name="x" type="radio"><span>No</span></label>
</div>
A demo: jsfiddle.net/qcxgwe66/

Check if checkbox checked property is not empty using jQuery

How can I check checkboxes checked property? If any of them is not checked, display this sentence in span: "you shoud select one of them". My validation don't work.
<label>
<input type="checkbox" name="chk[]" id="chk[]" />male
</label>
<label>
<input type="checkbox" name="chk[]" id="chk[]" />female
</label>
<script>
if ($('input[name="chk[]"]:checked').length < 0) {
$("#textspan").html('you shoud select one of them');
}
</script>
As far as your specific question goes, when no checkbox is checked $('input[name="chk[]"]:checked').length is 0, not negative - so you should change the condition from if ($('input[name="chk[]"]:checked').length < 0) to if ($('input[name="chk[]"]:checked').length == 0)
Full example
Other than that, some side notes:
1. I'd use radio buttons (as it is more suitable for your current male / female selection).
2. You have the same ID (chk[]) twice, which renders your HTML invalid.
3. The [] characters in the ID are not permitted in HTML 4.1 standards, and do not suit the convention.
I took the liberty of changing the code a bit, as your HTML is a bit strange.
Working example: http://jsfiddle.net/a4jzvoou/
HTML:
<div>
<input type="checkbox" class='gender' id="male">male</input>
<input type="checkbox" class='gender' id="female">female</input>
</div>
<button class="validate">Validate</button>
JS:
$(function() {
$('.validate').click(function(event) {
var checkedCount = ($('input[class="gender"]:checked').length))
})
});

I want to use the text of radio inputs. How can i get it using jQuery or JavaScript

I want to use the text 5 and 6 shown below. I cant modify the html as it is auto-generated and there are many other radios with the same structure. How can i achieve this using jQuery or JavaScript and store them as variables.
<label class="radio">
<label style="display: none;">
<input type="radio" name="x_keeper1_price" id="x_keeper1_price_0" value="21"/>
</label>
5
</label>
<label class="radio">
<label style="display: none;">
<label style="display: none;">
<input type="radio" name="x_Defd5_price" id="x_Defd5_price_0" value="28"/>
</label>
</label>
6
</label>
If your text after the radio button is html code, this is a better solution:
var text = $("#x_keeper1_price_0") //the radio button
.closest("label.radio") //the label with class=radio)
.html() //the html code
.replace(/<label[\d\D]+<\/label>/, '');
/* Removing the "second" label and its content.
That will get the text after the radio button. */
alert(text);
jsfiddle: http://jsfiddle.net/72KcV/3/
For this specific markup, you can use the following jQuery code:
$('label.radio').each(function(){
console.log($(this).contents()[2].nodeValue)
});
http://jsfiddle.net/eKG22/
You can do the following
$('.radio').text()
see a working solution here: http://jsfiddle.net/TfP5X/
Because we are using a class to select the text, you might want to loop over the selector and do something with each value like so.
var items = $('.radio');
$.each(items, function(i, item) {
var text = $(item).text();
//do something with text
});

Getting the selected radio without using "Id" but "name"

I was trying to get selected radio button by using "document.getElementByName('nameOfradio')" because all of the radio buttons share the same name. But, nothing happened. I tried the same thing with document.getElementById('nameOfradio') and worked well.However, I had to give unique id for all of the radio buttons. So that, it turns ugly when i have 20 radio buttons. As a result, what I wanted is making a shortcut. How can i get the value of selected radio button by using their "name"? Codes;
Html
<input type="radio" name="nameOfradio" value="onm1" /> 1
<input type="radio" name="nameOfradio" value="onm2" /> 2
<input type='button' onclick='radio3()' value='Submit' />
</form>
Ajax(relavant part of radio3())
var radioPushed = document.getElementByName('nameOfradio').value;
var queryString = "?radioPushed=" + radioPushed;//to send the value to another file
ajaxRequest.open("GET", "radio_display.php" + queryString, true);
ajaxRequest.send(null);
As i said document.getElementById worked but it requires too much work:( How can i make it simplier by using common feature of radio buttons, instead of giving them unique id? A short explanation why i could not make it would be very helpful(new in javascript and ajax)
This line:
document.getElementByName('nameOfradio').value
should be:
document.querySelector('input[name=nameOfradio]:checked').value;
using querySelector
Note that CSS pseudo-classes are accessed by a colon (:).
document.querySelector('input[name=nameOfRadio]:checked').value
Eg:-
<form>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
document.querySelector('input[name=gender]:checked').value
Also, you can add a checked attribute to a default radio button among the group of radio buttons if needed
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
Save yourself some pain in the later js dev and use a js library like jQuery. Then you can do something like $('input[name=radioName]:checked').val()
This is exactly why you should use a javascript library.
document.querySelector('input[name=nameOfradio]');
for example is not supported before IE8.
Let the library handle the browser craziness.
In jQuery you can just use $('input[name=radioName]:checked').val() or $("form").serialize() and be done with it.
You can use the class property if your looking for a quick solution. Many elements can have the same class. use the command:
document.getElementsByClass('nameOfradio');
In addition you should use the correct form of getting elements by name which is:
document.getElementsByName('nameOfradio');
You can also use the following code to find the selected radio value as follows:
radioObj=document.getElementsById('nameOfradio');
var radioLength = radioObj.length;
if(radioLength == undefined) {
if(radioObj.checked) {
return radioObj.value;
} else {
return "";
}
}
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";

Categories