Can I somehow insert the required attribute into an input field only if a certain radio is checked?
I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.
My input looks like this:
<input type="text" name="ladder-meters" id="ladder-meters">
and should like this at the onchange event on the radio
<input type="text" name="ladder-meters" id="ladder-meters" required>
document.getElementById("ladder").addEventListener('change', function(){
document.getElementById("ladder-meters").required = this.checked ;
})
Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked with !this.checked
This may need some adjustment to suit your specific project.
This will work with this checkbox:
<input type='checkbox' id='ladder' name='ladder' />
Tried F. Orvalho, didn't work for me, I had to use
$('#ladder').change(function () {
if(this.checked) {
$('#ladder-meters').prop('required', true);
} else {
$('#ladder-meters').prop('required', false);
}
});
It could be usefull. Thx to F. Orvalho for the structure
Easy to achieve with jQuery:
$('#ladder').change(function () {
if($(this).is(':checked') {
$('#ladder-meters').attr('required');
} else {
$('#ladder-meters').removeAttr('required');
}
});
Related
I am trying to change the attribute name="" value of an input field that is toggled once a check box is set and a toggled input is shown and filled out.
User checks a check box, once the check box is checked an input field shows where the title once was. I got this part covered.
Once the input field shows, I want to change the name attribute in that input field with the value the user inputs all before submission of form.
Here is the code I have tried...
document.getElementById('custom-check-box').addEventListener('click', function() {
if (this.checked) {
document.getElementById('custom-span').innerHTML = '<input type="text" id="customInputName" name="customInputName" placeholder="Name the custom attribute">';
} else {
document.getElementById('custom-span').innerHTML = 'Custom: ';
}
});
// this bit of code is not working as intended. I want to get the input
// value after the user changes or focus out of the input and then have that
// value input into the name attribute for the same input.
document.getElementById('customInputName').addEventListener('change', function() {
if (this.onChange) {
let value = document.getElementById('customInputName').value;
this.setAttribute("name", value);
}
});
<div title="'.$title.'" class="input-info">
<span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>
Error: Cannot read property 'addEventListener' of null
I think it is because the input is not set yet in the DOM. Should I set the input in HTML, hide it and then change the name attribute and then show it?
Any help would be greatly appreciated as I am a bit of a beginner with JavaScript.
Thank you in advance!
SEE ACCEPTED ANSWER FOR UPDATE ON WORKING CODE. -> Second snippit was added an edit to #CertainPerformance code that works better for my use.
I'd create the <input> outside of any of the handlers, and give it the listener which assigns its value to its name. When the checkbox is checked, append the input to the container, otherwise clear the container:
const input = document.createElement('input');
input.name = 'customInputName';
input.placeholder = 'Name the custom attribute';
const customSpan = document.getElementById('custom-span');
document.getElementById('custom-check-box').addEventListener('click', function() {
if (this.checked) {
customSpan.textContent = '';
customSpan.appendChild(input);
} else {
customSpan.textContent = 'Custom: ';
}
});
input.addEventListener('change', function() {
input.name = input.value;
});
<div title="'.$title.'" class="input-info">
<span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>
I want to display a text box using JavaScript when the "Other" option is checked from a group of checkboxes. I'm using razor pages with asp.net core 2.2
I'm using the following script but it is not working.
function onSelectChange() {
var sel = document.getElementById('QuestionOptionId');
var strUser = sel.options[sel.selectedIndex].text;
if (strUser.startsWith('Other'))
document.getElementById('textBox').disabled = false;
else
document.getElementById('textBox').disabled = true;
}
</script>
Fruits.cshtml ( razor page view file)
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange()" /> #option.Text<br />
}
QuestionOptions is a selectList:
Value=1 Text= Apple,
Value=2 Text= Kiwi,
Value=3 Text =Other
whenever the user checks the checkbox for "Other", it should display a textbox.
What am I doing wrong here? I have read so many other answers but not able to figure out this one.
Update-1
I don't know why the post is not showing the textbox control...
I'm pasting it here again, it is outside the foreach loop. I have removed the angle brackets as I think it is mixing with formatting.
input type="text" id="textBox" name="response" disabled="disabled"
Full disclosure: I have never used Razor pages or asp.net
I'm having a hard time following how your javascript is detecting whether the other option is checked. It seems like your Fruits.cshtml is going to generate three separate inputs with the same "QuestionOptionId" id.
Also, your Fruits.cshtml snipped doesn't include the code for the textbox you'd like to enable, though I'm assuming you have a textbox with id "textBox" in the compiled HTML that you'd like to enable.
I would change your script out for this:
function onSelectChange(element) {
if (element === element.parentNode.querySelector(".other")) {
console.dir(element);
if (element.checked) {
document.getElementById("textBox").disabled = false;
} else {
document.getElementById("textBox").disabled = true;
}
}
}
You'll need to add the "other" class to your applicable "Other" input checkbox. You'll also need to change your Fruits.cshtml snippet so that the "onclick" function also passes the applicable element into the script.
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange(this)" /> #option.Text<br />
}
Here's a working example of the compiled code: https://codepen.io/bourn404/pen/yWVLdx
Try the following modification in the view and the javascript:
Add the label outside the input
#foreach (var option in Model.QuestionOptions)
{
<Lable>
<input type="checkbox" asp-for="QuestionOptionId" id="QuestionOptionId" value="#option.Value" /> #option.Text
</Lable>
<br />
}
<div>
<input type="text" id="textbox" disabled="disabled" />
</div>
Use $(this).parent().text().trim() to get the text
$('input:checkbox').on('click', function () {
if ($(this).parent().text().trim() === "Other") {
$('#textbox').removeAttr("disabled");
}
});
Update
If you want to hide the text box and hide the textbox when you uncheck the "other option , firstly you could change the disabled attribute to hidden ,and then determine if the text box contains hidden attribute in js like below :
<input type="text" id="textbox" hidden />
if ($(this).parent().text().trim() === "Other")
{
if ($('#textbox').is(':hidden')) {
$('#textbox').removeAttr("hidden");
}
else {
$('#textbox').attr("hidden", "hidden");
}
}
I have an input and a checkbox. I have managed to change the value in the input on clicking the checkbox, and un clicking etc which works fine.
I'm looking to auto set the checkbox to be checked on page load only if the input value = yes, as this input value is being loaded dynamically via php and may not be yes.
HTML
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">
JQUERY
$('#yourCheckboxId').click(function() {
if ($('#yourCheckboxId').is(':checked')){
$('#inputId').val('yes');
}
if (!$('#yourCheckboxId').is(':checked')){
$('#inputId').val('no');
}
});
You'll notice that even though the value in the input is set to yes, on page load, the checkbox isn't checked. This is what I have so far, see jsfiddle here: http://jsfiddle.net/0z9agrw8/1/
Thanks
var input = $('#inputId').val()
if(input === "yes"){
$("#yourCheckboxId").prop('checked', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">
Do this on page load:
if($('#inputId').val() == 'yes') {
$('#yourCheckboxId').prop('checked', true);
}
If you always want it to be checked on page load, you can simply add the "checked" attribute
eg
<input type="checkbox" id = "yourCheckboxId" checked>
If it's more complicated than that, the other answers will work nicely
I have a situation where i want to validate the text entered into a input text field. This is the HTML code:
<div id="err_title" style="display:none;">Please enter a valid Number.</div>
<input type="radio" id="txt_a-radio" value="valueA" checked="checked">
<input type="text" id="txt_a">
<input type="radio" id="txt_b-radio" value="valueB">
<input type="text" id="txt_b" disabled>
By default #txt_b field will be disabled, when user clicks on #txt_b-radio button #txt_b will be enabled and #txt_a will be disabled.
The condition for validation is:
#txt_a can contain only 12 digit number
#txt_b can contain only 20 digit number
Validation should happen once user enters value in enabled field then clicks anywhere outside. If value entered by user is not valid error message #err_title should display.
Suppose if user enters value for #txt_a and then clicks on #txt_b-radio button then validation shouldn't happen since user has switched the input field.In this case #txt_a should be disabled and txt_b enabled.
I have tried with the following code:
$('#txt_a').change(function() {
custNumber = $('#txt_a').val(); expression = /^[0-9]{12}$/;
if(custNumber === '') {
$("#err_title").css('display', 'none');
} else if ((!custNumber.match(regexp))) {
$("#err_title").css('display', 'block');
} else {
$("#err_title").css('display', 'none');
}
});
$input1 = $('input[name="input1"]');
$input2 = $('input[name="input2"]');
$checkbox = $('input[name="checkbox"]');
$input1.on('change', function(e) {
var isValid = this.value.length >= 12;
this.classList.toggle('notValid', !isValid);
})
$checkbox.on('change', function(e) {
$input2.prop('disabled', !this.checked);
})
input.notValid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input1" />
<input type="text" name="input2" disabled />
<input type="checkbox" name="checkbox" />
NOTE:
In example above, I'm mixing vanillia JS, with jQuery. I would recommend avoiding it - I did that to show You how easy (well not always...) it is to do such a simple thing without jQuery.
Basically, if You want to do simple stuff like that, I would recommend to give up on jQuery.
ANSWER:
You are looking for jQuery change event. It triggers once input loose focus.
$(your_input).on('change', function(e) {...} )
You can validate input length like (function inside listener) :
var isValid = this.value.length === 12
Same goes with disabled/enabled input.
You have to attach event listener to checkbox
$(your_checkbox).on('change', function(e) {...} )
then You can get state of checkbox :
var isChecked = this.checked
and disable/enable Your input
$(your_input).attr('disabled', !isChecked)
i would like to remove a hidden field from the form using jquery based on hidden field value.
please look the below html:
<input type="hidden" name="myvalue[]" value="value1"/>
<input type="hidden" name="myvalue[]" value="value2"/>
<input type="hidden" name="myvalue[]" value="value3"/>
i have jquery function which returns me the above value example:
$('#getValue').click(function(){
.... processing code here.....
return valueOfHiddenField;
});
now i would like to remove the hidden field from the form based on the value return by the getValue
so if the method returns me value1 then any input hidden field in the form with value as value1 should be removed. in this case the first input field of my html above.
any help or suggestion would be a great help ... thanks in advance
$('input[type="hidden"][value="+YOUR_VALUEVAR+"]').remove();
fiddle: http://jsfiddle.net/9tsgy/
You can iterate over input:hidden elements to check values and remove() based on value,
$("input:hidden").each(function () {
if (this.value == "value1") { // your condition here
$(this).remove()
}
}
$('#getValue').click(function () {
$(document).find("input[type=hidden]").each(function () {
if ($(this).value == 'Your Value') {
$(this).remove();
}
});
return valueOfHiddenField;
});
You can also do like this:
let hiddenValue = $(this).val();
$('input[type="hidden"][value="'+hiddenValue+'"]').remove();
Get the value of a hidden field and then use it dynamically and remove specific <input type="hidden">