Here is the problem I am trying to solve:
I have a long list of questions.
Each question includes a response section, which consist of 4 radiobuttons (Yes, No, Not Seen and Not Applicable) and two textareas;
Now, textarea "observation" is disabled by default. Only user's response "No" enables this textarea.
Question: How to apply the same logic to every textarea "observation" throughout the entire set of questions.
What I have at the moment is:
A. HTML for Response buttons
<div id="Response">
<label><input type="radio" name="Radio419" value="Y" id="Radio_419Y" onchange='radioChange(this)'>Yes</label>
<label><input type="radio" name="Radio419" value="N" id="Radio_419N" onChange='radioChange(this)'>No</label>
<label><input type="radio" name="Radio419" value="NS" id="Radio_419NS" onChange='radioChange(this)'>Not Seen</label>
<label><input type="radio" name="Radio419" value="NA" id="Radio_419NA" onChange='radioChange(this)'>Not Applicable</label>
</div>
B. HTML for Textboxes
<span id="responseDetails">
<div id="Comment">
<label for="comment">Comment:</label>
<textarea name="comment" id="Comm419"</textarea></div>
<div id="Observation">
<label for="observation">Observation:</label>
<textarea name="observation" id="Obs419"</textarea></div>
</span>
C. JS for processing THIS question only
<script type="text/javascript">
document.radioChange = function (button)
{if(button.checked ) {if (button.value === "N")
{document.getElementById("Obs419").removeAttribute("disabled")}
else
{document.getElementById("Obs419").setAttribute("disabled",true)}}}
</script>
Now as it is apparent I can only apply this to question 419, referring to textbox Observation (Obs419).
How do I apply JS to cover other questions, because textareas are going to be the same throughout the questionnaire. Textarea id changes with every new question (Obs420, Obs421 etc).
Thank you in advance.
If you can pass the id into radioChange() function like this onchange='radioChange(this, '419')'
<label><input type="radio" name="Radio419" value="Y" id="Radio_419Y" onchange='radioChange(this, '419')'>Yes</label>
Then you will get that id of radio button(which would be clicked) inside radioChange() and with that dynamic id you need to just write below code.
document.radioChange = function (button, id)
{if(button.checked ) {if (button.value === "N")
{document.getElementById("Obs"+id).removeAttribute("disabled")}
else
{document.getElementById("Obs"+id).setAttribute("disabled",true)}}}
UPDATE
First of all, your both textarea tags are not closed
<textarea name="comment" id="Comm419" </textarea></div>
//-----------------------------------^
Second you will have to pass id within double quote "", like
onchange='radioChange(this, "419")'
Here is the DEMO with passing dynamic id.
Related
I am trying to write a JavaScript code that prints whatever is present in the body-tag again when you click on the add button. The basic idea is to add authors. For example suppose there is only 1 author then the user does not click on the add button but only selects whether he is a student or a teacher. Now suppose there are 3 authors for a particular instance then he selects whether he is a student or a teacher for author 1 and then clicks "add" button.Now the above set of questions again appears for author 2 and now user can select whether the 2nd author is student or teacher. For the 3rd author the user needs to click "add" again which appears below the 2nd author which allows user to click whether the 3rd author is student or teacher. Infact this can be carried out for n number of authors.Basically the authors should appear one after the other in sequence. I could only achive it for 1st user
<html>
<head>
<title>Authors</title>
<script>
function addauthor()
{
console.log('function is working');
var no;
but = document.getElementById("addauth");
no = Number(but.value)+1;
document.getElementById('next').innerHTML='<p><div>'+no+'</div> \
<p>Whom do you want to add ? </p> \
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label> \
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label> \
<div id=""></div> \
</p> \
<p id="next"> \
<button id="addauth" onclick="addauthor()" value="'+no+'">Add</button> \
</p>';
}
</script>
</head>
<body>
<p><div>1</div>
<p>Whom do you want to add ? </p>
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label>
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label>
<div></div>
</p>
<p id="next">
<button id="addauth" onclick="addauthor()" value="1">Add</button>
</p>
</body>
</html>
I am a newbie to JavaScript. Although the code works partially I know the code is inefficient but I am not sure of how to do it. If anyone knows a better or an efficient method or algorithm please suggest me.
This is where I am going wrong for author 3 and till author n
What's going on is that you are rewriting the #next html element instead of concatenating to it. You can concatenate to the HTML element. You also need to move the button outside of the logic you want to append to the DOM. I have put a wrapper around the elements requiring to be appended called person-container:
HTML
<div id="person-container">
<div>1</div>
<p>Whom do you want to add ? </p>
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label>
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label>
</div>
<p id="next">
<button id="addauth" onclick="addauthor()" value="1">Add</button>
</p>
JS
var no = 1;
function addauthor()
{
console.log('function is working');
but = document.getElementById("addauth");
no++;
var newEle = document.createElement('div');
newEle.classList.add = "person";
newEle.innerHTML ='<br><div>'+no+'</div> \
<p>Whom do you want to add ? </p> \
<label><input type="radio" name="add" value="student" onchange="showForm()">Student</label> \
<label><input type="radio" name="add" value="teacher" onchange="showForm()">Teacher</label> \
<div id=""></div><br>';
document.getElementById('person-container').appendChild(newEle);
}
See the fiddle: https://jsfiddle.net/gt4c6zpL/4/
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"
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/
I want to hide a div (AppliedCourse), when radi button value is Agent. I wrote below code but it is not working.
Any idea?
$('#HearAboutUs').click(function() {
$("#AppliedCourse").toggle($('input[name=HearAboutUs]:checked').val()='Agent');
});
<tr><td class="text"><input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other</td></tr>
Either your HTML is incomplete or your first selector is wrong. It is possible that your click handler is not being called because you have no element with id 'HeadAboutUs'. You might want to listen to clicks on the inputs themselves in that case.
Also, your logic is not quite right. Toggle hides the element if the parameter is false, so you want to negate it using !=. Try:
$('input[name=HearAboutUs]').click(function() {
var inputValue = $('input[name=HearAboutUs]:checked').val()
$("#AppliedCourse").toggle( inputValue!='Agent');
});
I have made a JSFiddle with a working solution: http://jsfiddle.net/c045fn2m/2/
Your code is looking for an element with id HearAboutUs, but you don't have this on your page.
You do have a bunch of inputs with name="HearAboutUs". If you look for those, you'll be able to execute your code.
$("input[name='HearAboutUs']").click(function() {
var clicked = $(this).val(); //save value of the input that was clicked on
if(clicked == 'Agent'){ //check if that val is "Agent"
$('#AppliedCourse').hide();
}else{
$('#AppliedCourse').show();
}
});
JS Fiddle Demo
Another option as suggested by #Regent is to replace the if/else statement with $('#AppliedCourse').toggle(clicked !== 'Agent');. This works too.
Here is the Fiddle: http://jsfiddle.net/L9bfddos/
<tr>
<td class="text">
<input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other
</td>
Test
$("input[name='HearAboutUs']").click(function() {
var value = $('input[name=HearAboutUs]:checked').val();
if(value === 'Agent'){
$('#AppliedCourse').hide();
}
else{
$('#AppliedCourse').show();
}
});
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))
})
});