Prevent text entry in textbox unless checkbox is checked - javascript

I'm trying to prevent text from being entered in a textbox unless a checkbox that corresponds with the textbox is checked.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
isOther.addEventListener("input", function (evt) {
// Checkbox must be checked before data can be entered into textbox
if (isOther.checked) {
document.getElementById("other").disabled = false;
} else {
document.getElementById("other").disabled = true;
}
});

Do not use disabled. Instead use readonly. During document load, uncheck and disable the inputs:
<input type="checkbox" id="isOther" />
<input type="text" id="other" readonly />
And use this script.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
other.readOnly = !isOther.checked;
});
other.addEventListener("focus", function (evt) {
// Checkbox must be checked before data can be entered into textbox
other.readOnly = !isOther.checked;
});
Longer version.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
if (isOther.checked) {
other.readOnly = false;
} else {
other.readOnly = true;
}
});
other.addEventListener("focus", function (evt) {
// Checkbox must be checked before data can be entered into textbox
if (isOther.checked) {
this.readOnly = false;
} else {
this.readOnly = true;
}
});
Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/1/
Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/

My solution uses jQuery library. Here's a fiddle: http://jsfiddle.net/8LZNa/
Basically I'm disabling the input on page load:
<input name="isOther" type="checkbox" id="isOther" /><br />
<input type="text" id="other" disabled/>
... and when isOther changes it will make sure it is checked, and change the state to enabled. Or change back to disabled.
$('input[name=isOther]').change(function(){
if($(this).is(':checked')) {
$("#other").removeAttr('disabled');
}
else{
$("#other").attr('disabled','disabled');
}
});

You can do this:
document.getElementById( 'isOther' ).onChange = function(){
document.getElementById("other").disabled = !this.checked;
};

Without the use of jQuery or disabled property:
HTML
<input type="checkbox" id="x" value="Enable textbox" onclick="test(this);" />
<input type="text" id="y" readonly />
JAVASCRIPT
function test(checkbox) {
if(checkbox.checked) {
document.getElementById('y').readOnly = false;
}
else {
document.getElementById('y').readOnly = true;
}
}

Related

How to validate JavaScript created element in asp.net core mvc

I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:

Listen for blank inputs and add a "disabled" attribute to a button until an input is noticed

I have a user input field that, if blank, I would like the submit button to be disabled until a key press in the input box is noticed. But, if they blank out the input box, then the button is disabled again.
So, I'd like to add the "disabled" attribute to this input button:
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
The input is from this HTML here:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
Note: I have onkeypress and oninput validation to prevent non-number inputs and allow only 2 decimal places.
I assume my JS would look like this to add the disabled attribute:
document.getElementById("mapOneSubmit").setAttribute("disabled");
My problem is, I can't find what event listener listens for "blank" inputs? Can you help me with that?
Thanks kindly!
Check this one as well.
function checkvalid(el)
{
//e.g i am preventing user here to input only upto 5 characters
//you can put your own validation logic here
if(el.value.length===0 || el.value.length>5)
document.getElementById("mapOneSubmit").setAttribute("disabled","disabled");
else
document.getElementById("mapOneSubmit").removeAttribute('disabled');
}
<input type='text' id ='inp' onkeyup='checkvalid(this)'>
<button id='mapOneSubmit' disabled>
Submit
</button>
Yet using the input event:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this);updateSubmit(this.value)">
Then in js
function updateSubmit(val) {
if (val.trim() == '') {
document.getElementById('mapOneSubmit').disabled = true;
}
else {
document.getElementById('mapOneSubmit').disabled = false;
}
}
You can find the below code to find the blank inputs
function isNumberKey(event) {
console.log(event.which)
}
var value;
function validate(target) {
console.log(target);
}
<form>
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
</form>
You can you set the enable/disable inside validate function.
function validate(elem) {
//validation here
//code to disable/enable the button
document.getElementById("mapOneSubmit").disabled = elem.value.length === 0;
}
Set the button disable on load by adding disabled property
<input type="submit" id="mapOneSubmit" value="Submit" disabled>
On your validate function just check if value of input field is blank then enable/disable the button
function validate(input){
input.disabled = input.value === "" ;
}
My problem is, I can't find what event listener listens for "blank" inputs?
You can disable the submit button at render, after that you can use the input event to determine whether the input value is empty or not. From there, you can set state of the submit button.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('mapOneUserInput');
textInput.addEventListener('input', handleTextInput, false);
textInput.addEventListener('keydown', validateInput, false);
});
function handleTextInput(event) {
const { value } = event.target;
if (value) {
enableSubmitButton(true);
} else {
enableSubmitButton(false);
}
}
// Refer to https://stackoverflow.com/a/46203928/7583537
function validateInput(event) {
const regex = /^\d*(\.\d{0,2})?$/g;
const prevVal = event.target.value;
const input = this;
setTimeout(function() {
var nextVal = event.target.value;
if (!regex.test(nextVal)) {
input.value = prevVal;
}
}, 0);
}
function enableSubmitButton(isEnable) {
const button = document.getElementById('mapOneSubmit');
if (isEnable) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
}
<input type="number" value="" id="mapOneUserInput">
<!-- Note that the input blank at render so we disable submit button -->
<input type="submit" id="mapOneSubmit" value="Submit" disabled>

Javascript check a radio button in form based on a text box value

I have a form which inserts and retrieves data from a google sheet.
Example:
I have two radio buttons on my form
<input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck"
value="1" onchange="RadioValInsert ()"/>
<input id="Rdio_2" name="RdioSelect" type="radio" class="FirstCheck"
value="2" onchange="RadioValInsert ()" />
when the above is clicked the value of the radio button is stored in a text box..the RadioValInsert () does it
<input type="text" id="DatafromRadio" name="DatafromRadio">
I am able to insert this value of 1 or 2 into the corresponding cell in google sheet.
When I want to EDIT it, I retrieve the data and the Textbox value is 1 or 2
The button which retrieves the data has a function to check the corresponding radio button based on the value of the Text box.
function RadioChk() {
var val = document.getElementById("DatafromRadio").value;
if (val == 1) {
document.getElementById("Rdio_1").checked = true;
}
if (val == 2) {
document.getElementById("Rdio_2").checked = true;
}
}
This is not working
Thanks in advance for your help
You are doing your check and uncheck related code inside RadioChk function however you haven't bind click event on radio inputs . If i correctly understood your question , here is how you can select and deselect your radio buttons.
function RadioValInsert() {
console.log('checked');
var val = document.getElementById("DatafromRadio").value;
if(val ==1 || val ==2){
uncheckAll();
document.getElementById("Rdio_"+val).checked = true;
}else{
uncheckAll();
console.log('choose only between 1 or 2');
}
}
function uncheckAll(){
let ele = document.getElementsByName("RdioSelect");
for(var i=0;i<ele.length;i++){
ele[i].checked = false;
}
}
<input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck"
value="1" onchange="RadioValInsert ()"/>
<input id="Rdio_2" name="RdioSelect" type="radio" class="FirstCheck"
value="2" onchange="RadioValInsert ()" />
<input type="text" id="DatafromRadio" name="DatafromRadio">
Try this example where radio selection and textbox value changes as per selection/input
document.addEventListener('DOMContentLoaded', function(dce) {
var radios = document.querySelectorAll('[name="RdioSelect"]');
var textbx = document.querySelector('[name="DatafromRadio"]');
radios.forEach(function(r) {
r.addEventListener('click', function(e) {
textbx.value = this.value;
});
});
textbx.addEventListener('input', function(e) {
radios.forEach(function(r) {
r.checked = (r.value === textbx.value);
});
});
var fillTxt = function(txt) {
textbx.value = txt;
textbx.dispatchEvent(new Event('input')); //<-- trigger event
};
fillTxt('2'); //<--- update text box
});
<input id="Rdio_1" name="RdioSelect" type="radio" value="1" />
<input id="Rdio_2" name="RdioSelect" type="radio" value="2" />
<input type="text" id="DatafromRadio" name="DatafromRadio" />
this works only if data is input physically in the text box - in my case the data is retrieved via a function and it populates the text box
In that, just trigger event on textbox

How to Disable input text on form?

I want to disable and enable input text if action add input text enable And if action edit input text disable
thanks
You can achieve this using the jQuery function prop() :
Javscript
var value = $('input').val();
if (value == null) {
$("input").prop('disabled', false);
} else {
$("input").prop('disabled', true);
}
Here is a demo: JsFiddle
Since you have not provided any snippet, I tried to replicate it witll following codes.
HTML
<input type = "text" id ="demoI">
<input type = "button" value = "Add" id = "_add">
<input type = "button" value = "Edit" id = "_edit">
JS
window.onload=function(){
var _getInput=document.getElementById("demoI");
var _getAdd = document.getElementById("_add");
var _getEdit = document.getElementById("_edit");
_getAdd.addEventListener('click',function(event){
_getInput.disabled = true;
})
_getEdit.addEventListener('click',function(event){
_getInput.disabled = false;
})
}
Check this jsFiddle
You can do this in your view.
if( $this->uri->segment(3) == 'add' ) {
<input type="text" name="myfield" disabled />
} else {
<input type="text" name="myfield" />
}
Try this code:
you can do this with java script only, there is no need to use jQuery
window.onload = function(){
var fname = document.getElementById("fname").value;
if(fname == '')
{
document.getElementById("fname").disabled = false;
}
else
{
document.getElementById("fname").disabled = true;
}
}
First Name: <input type="text" name="fname" id="fname" >

Disable form button unless all text input fields are filled in

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.
I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.
<script>
$(function () {
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
$('#button').prop('disabled', this.value == "" ? true : false);
})
});
</script>
I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
var disable = false;
$('input:text').each(function(){
if($(this).val()==""){
disable = true;
}
});
$('#button').prop('disabled', disable);
});
Demo
The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.
$('input:text').keyup(function () {
$('#button').prop('disabled', allFieldsAreFilled());
});
function allFieldsAreFilled() {
var allFilled = true;
// check all input text fields
$("#yourForm input:text"]).each(function () {
// if one of them is emptyish allFilled is no longer true
if ($(this).val() == "") {
allFilled = false;
}
});
return allFilled;
}
Try this:
$(function() {
var bool = true, flag = false;
$('#button').prop('disabled', bool); // use prop to disable the button
$(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs
$('input:text').each(function() { // loop through each text inputs
bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values
if(bool)
return flag;
});
$('#button').prop('disabled', bool); // and apply the boolean here to enable
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />

Categories

Resources