How to disable/enable input field on click with jQuery - javascript

How to properly enable/disable input field on click with jQuery?
I was experimenting with:
$("#FullName").removeAttr('disabled');
which removes disabled="disabled" from this input field:
<input id="FullName" style="width: 299px" value="Marko" disabled="disabled" />
But how to add it again with click on another button or how to disable input field on click?

For jQuery version 1.6+ use prop:
$('#elementId').click(function(){
$('#FullName').prop('disabled', true\false);
});
For older versions of jQuery use attr:
$('#elementId').click(function(){
$('#FullName').attr('disabled', 'disabled'\'');
});

$("#FullName").prop('disabled', true);
Will do.
But keep in mind after you disable it (by the above code) onclick handler wont work as its disabled. To enable it again add $("#FullName").removeAttr('disabled'); in the onclick handler of another button or field.

$('#checkbox-id').click(function()
{
//If checkbox is checked then disable or enable input
if ($(this).is(':checked'))
{
$("#to-enable-input").removeAttr("disabled");
$("#to-disable-input").attr("disabled","disabled");
}
//If checkbox is unchecked then disable or enable input
else
{
$("#to-enable-input").removeAttr("disabled");
$("#to-disable-input").attr("disabled","disabled");
}
});

another simple method to enable/disable input feild
$("#anOtherButton").click(function() {
$("#FullName").attr('disabled', !$("#FullName").attr('disabled'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input id="FullName" style="width: 299px" value="Marko" disabled="disabled" />
<br>
<br>
<input type="button" id="anOtherButton" value="disable/enable" />

This should do it.
$("#FullName").attr('disabled', 'disabled');
Shiplu is correct, but use this if you have are not using jquery 1.6+

$("#anOtherButton").click(function(){
$("#FullName").attr('disabled', 'disabled');
});
.attr( attributeName, value) function
Set one or more attributes for the set of matched elements

To toggle a field between disabled and enabled, try this:
$('#toggle_button').click(function () {
$('#FullName').prop("disabled",
function (i, val) {
return !val;
});
})

Related

How to make button enable, when there is value in input date field

I have one input date field and one button, I want to make the button enable when there is value in input date field. How to make in JavaScript or jQuery
check if input has value using val(). hope this helps
function check(val)
{
var btn = $('.submit')
if(val)
{
btn.removeAttr("disabled");
}
else
btn.attr("disabled", "disabled");
}
$('.date').change(function(e){ // change button disabled property if user provides input
check($(this).val());
})
check($('.date').val()); // Function to check input has value
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<input class="date" type="date">
<button class="submit">Submit</button>
You can use jquery function .on()
$(document).ready(function(){
$("input[name='date']").on("change", function(){
if($(this).val() != "")
$("input[name='submit']").removeAttr("disabled");
else
$("input[name='submit']").attr("disabled", "disabled");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="date" />
<input type="button" name="submit" disabled="disabled" value="submit"/>
</form>
here I initially set attribute disabled then remove it once there's input and it's not empty input. If it's empty, I re-add that attribute.

Checkboxs disabled with jquery not working as intended

i have some checkboxes that are displayed by doing a select in database that represents tables of a restaurant. Those tables that are already reserved i add them an disabled attribute. The problem with my script is that i only want to select three tables max and that means i need to add disabled atribute to the other to block them. and when i want to deselect those 3 already selected i need to remove the disabled attribute. Problem is that it removes the attribute from all tables even those that are reserved and selected from database.
Here is my script:
JSFIDDLE HERE
<script type="text/javascript">
var $checks = $(".table").change(function () {
if ($checks.filter(":checked").length<3)
{
$(".formular").toggle($checks.filter(":checked").length>0);
$checks.not(":checked").removeAttr("disabled");
}
else
{
$checks.not(":checked").attr("disabled", "disabled");
}
});
</script>
Added a class .ignore to the input disabled from start and in js binding change event only to checkboxes without the ignore class as mentioned by #lolka_bolka
HTML
<input type="checkbox" class="bowling ignore" disabled/>
<input type="checkbox" class="bowling ignore" disabled/>
<input type="checkbox" class="bowling"/>
<input type="checkbox" class="bowling"/>
JS
var $checks = $(".bowling:not(.ignore)").change(function () {
if ($checks.filter(":checked").length < 3) {
$(".formular").toggle($checks.filter(":checked").length > 0);
$checks.not(":checked").removeAttr("disabled");
} else {
$checks.not(":checked").attr("disabled", "disabled");
}
});
:not(foo){} will match anything that isn't foo, including html and
body. Source
Demo

How do I check if a file has been selected in a <input type="file"> element?

I have multiple checkboxes and a file upload input. I would like to re-enable a button if one or more checkbox's are checked AND if the input value is not null.
Here is a link to bootply
Here my html
<div class="upload-block">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="file" id="InputFile">
<button id="upload-btn" type="button blue-button"
class="btn blue-button" disabled>Submit</button>
</div>
Here is my javascript starting point:
Updated via Karl
Bind a change event on all input and then use some condition:
$('.upload-block input').change(function() {
$('#upload-btn').prop(
'disabled',
!($('.upload-block :checked').length && $('#InputFile').val()));
});
Example
This works for all the checkboxes and #InputFile has a value other than none. i.e. where a file has been chosen. However this does not work in IE9
How can I update this to work in IE9?
Bind a change event on all input and then use some condition:
$('.upload-block input').change(function() {
$('#upload-btn').prop(
'disabled',
!($('.upload-block :checked').length && $('#InputFile').val()));
});
Example
Like this:
if($('#InputFile').val().length){
//do your stuff
}
You can better use by using $.trim() method not to allow (trim) spaces:
if($.trim($('#InputFile').val()).length){
//do your stuff
}
Pure JS:
<input type="file" id="InputFile">
<button onclick="buttonSubmitClicked(event)">Submit</button>
<script>
function buttonSubmitClicked(event) {
if (!document.getElementById("InputFile").value) {
event.preventDefault();
alert("Please choose a file!");
} else {
alert("File've been chosen");
}
}
</script>
jsfiddle: check it out
$('.upload-block input').change(function() {
if ($('.upload-block :checked').length && $('#InputFile').val() ) {
$('#upload-btn').prop('disabled',false);
}
else {
$('#upload-btn').prop('disabled',true);
}
});
No need of separate selectors for checkbox and input file .upload-block input is enough to catch catch both the checkbox and file value change
I would apply the validation to all elements involved. This way changing either the checkboxes or the input will update disabled
$('#InputFile, .upload-block :checkbox').change(function(){
var isValid= $('.upload-block :checkbox:checked').length && $('#InputFile').val();
$('#upload-btn').prop('disabled',isValid);
});

jQuery: trigger click or focus input field

I have a page with multiple divs that all look like the example below.
Each div contains a field, a hidden field and a button.
How can I achieve that by click on the button the (visible) input field gets triggered ?
I need to trigger either a click or focus as both fire the same function.
Each button in question has the class="triggerBtn" and the corresponding input field has the class="inputField".
Example div:
<div>
<input type="text" class="inputField" id="field1" name="field1" />
<input type="hidden" name="field1" />
<button type="button" class="btn btn-primary triggerBtn">Find</button>
</div>
I guess you want:
$(".triggerBtn").click(function () {
$(this).closest('div').find('.inputField').focus();
});
add
Onclick="function()" see here
if you need to trigger it manually using jquery you can to this by
$("#field1").trigger("click");
see also here
$(".triggerBtn").on("click",function(e){
$(this).closest("div").find(".inputField").click();
//or $(this).closest("div").find(".inputField").focus();
});
$(".triggerBtn").parent().children("input[type:text]").first().focus()
Updated Jsfiddle: http://jsfiddle.net/ZmL4y/3/
$(document).on("click",".triggerBtn", function() {
var inputField = $(this).closest('div').find('.inputField');
if($(inputField).is(":visible"))
{
$(inputField ).focus();
}
});

How to check a radio button with jQuery?

I try to check a radio button with jQuery. Here's my code:
<form>
<div id='type'>
<input type='radio' id='radio_1' name='type' value='1' />
<input type='radio' id='radio_2' name='type' value='2' />
<input type='radio' id='radio_3' name='type' value='3' />
</div>
</form>
And the JavaScript:
jQuery("#radio_1").attr('checked', true);
Doesn't work:
jQuery("input[value='1']").attr('checked', true);
Doesn't work:
jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
Doesn't work:
Do you have another idea? What am I missing?
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.
Try this.
In this example, I'm targeting it with its input name and value
$("input[name=background][value='some value']").prop("checked",true);
Good to know: in case of multi-word value, it will work because of apostrophes, too.
Short and easy to read option:
$("#radio_1").is(":checked")
It returns true or false, so you can use it in "if" statement.
One more function prop() that is added in jQuery 1.6, that serves the same purpose.
$("#radio_1").prop("checked", true);
Try this.
To check Radio button using Value use this.
$('input[name=type][value=2]').attr('checked', true);
Or
$('input[name=type][value=2]').attr('checked', 'checked');
Or
$('input[name=type][value=2]').prop('checked', 'checked');
To check Radio button using ID use this.
$('#radio_1').attr('checked','checked');
Or
$('#radio_1').prop('checked','checked');
Use prop() mehtod
Source Link
<p>
<h5>Radio Selection</h5>
<label>
<input type="radio" name="myRadio" value="1"> Option 1
</label>
<label>
<input type="radio" name="myRadio" value="2"> Option 2
</label>
<label>
<input type="radio" name="myRadio" value="3"> Option 3
</label>
</p>
<p>
<button>Check Radio Option 2</button>
</p>
<script>
$(function () {
$("button").click(function () {
$("input:radio[value='2']").prop('checked',true);
});
});
</script>
The $.prop way is better:
$(document).ready(function () {
$("#radio_1").prop('checked', true);
});
and you can test it like the following:
$(document).ready(function () {
$("#radio_1, #radio_2", "#radio_3").change(function () {
if ($("#radio_1").is(":checked")) {
$('#div1').show();
}
else if ($("#radio_2").is(":checked")) {
$('#div2').show();
}
else
$('#div3').show();
});
});
Try This:
$("input[name=type]").val(['1']);
http://jsfiddle.net/nwo706xw/
Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments. Make sure you invoke .change(), otherwise all the "on change" bindings will ignore this event.
$("#radio_1").prop("checked", true).change();
You have to do
jQuery("#radio_1").attr('checked', 'checked');
That's the HTML attribute
Try this
$(document).ready(function(){
$("input[name='type']:radio").change(function(){
if($(this).val() == '1')
{
// do something
}
else if($(this).val() == '2')
{
// do something
}
else if($(this).val() == '3')
{
// do something
}
});
});
If property name does not work don't forget that id still exists. This answer is for people who wants to target the id here how you do.
$('input[id=element_id][value=element_value]').prop("checked",true);
Because property name does not work for me. Make sure you don't surround id and name with double/single quotations.
Cheers!
We should want to tell it is a radio button.So please try with following code.
$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);
Yes, it worked for me like a way:
$("#radio_1").attr('checked', 'checked');
This answer is thanks to Paul LeBeau in a comment. I thought I'd write it up as a proper answer since there surprisingly wasn't one.
The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:
$(".js-my-radio-button").trigger("click");
This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change on the radio button.
Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.
Try this with example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>
<script>
$(document).ready(function () {
$('#myForm').on('click', function () {
var value = $("[name=radio]:checked").val();
alert(value);
})
});
</script>
$("input[name=inputname]:radio").click(function() {
if($(this).attr("value")=="yes") {
$(".inputclassname").show();
}
if($(this).attr("value")=="no") {
$(".inputclassname").hide();
}
});
Get value:
$("[name='type'][checked]").attr("value");
Set value:
$(this).attr({"checked":true}).prop({"checked":true});
Radio Button click add attr checked:
$("[name='type']").click(function(){
$("[name='type']").removeAttr("checked");
$(this).attr({"checked":true}).prop({"checked":true});
});
Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:
$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set
I use this code:
I'm sorry for English.
var $j = jQuery.noConflict();
$j(function() {
// add handler
$j('#radio-1, #radio-2').click(function(){
// find all checked and cancel checked
$j('input:radio:checked').prop('checked', false);
// this radio add cheked
$j(this).prop('checked', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="section">
<legend>Radio buttons</legend>
<label>
<input type="radio" id="radio-1" checked>
Option one is this and that—be sure to include why it's great
</label>
<br>
<label>
<input type="radio" id="radio-2">
Option two can be something else
</label>
</fieldset>
Try this
var isChecked = $("#radio_1")[0].checked;
I've just have a similar problem, a simple solution is to just use:
.click()
Any other solution will work if you refresh radio after calling function.
function rbcitiSelction(e) {
debugger
$('#trpersonalemail').hide();
$('#trcitiemail').show();
}
function rbpersSelction(e) {
var personalEmail = $(e).val();
$('#trpersonalemail').show();
$('#trcitiemail').hide();
}
$(function() {
$("#citiEmail").prop("checked", true)
});
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');
I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.
Example is in here:
$(function () {
$('#CostAnalysis input[type=radio]').click(function () {
var value = $(this).val();
if (value == "Supply & Lay") {
$('#ul-suplay').empty();
$('#ul-suplay').append('<fieldset data-role="controlgroup"> \
http://jsfiddle.net/m7hg2p94/4/
attr accepts two strings.
The correct way is:
jQuery("#radio_1").attr('checked', 'true');
In addition, you can check if the element is checked or not:
if ($('.myCheckbox').attr('checked'))
{
//do others stuff
}
else
{
//do others stuff
}
You can checked for unchecked element:
$('.myCheckbox').attr('checked',true) //Standards way
You can also uncheck this way:
$('.myCheckbox').removeAttr('checked')
You can checked for radio button:
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
I used jquery-1.11.3.js
Basic Enable & disable
Tips 1: (Radio button type common Disable & Enable)
$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true);
Tips 2: ( ID selector Using prop() or attr())
$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);
jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);
Tips 3: ( Class selector Using prop() or arrt())
$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);
jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);
OTHER TIPS
$("#paytmradio").is(":checked") // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled
$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
$("input:checked", "#paytmradio").val() // get the checked value
index.html
<div class="col-md-6">
<label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
<div id="paymenttype" class="form-group" style="padding-top: inherit;">
<label class="radio-inline" class="form-control"><input type="radio" id="paytmradio" class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
<label class="radio-inline" class="form-control"><input type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
</div>
</div>
try this
$("input:checked", "#radioButton").val()
if checked returns True
if not checked returns False
jQuery v1.10.1
Some times above solutions do not work, then you can try below:
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));
Another way you can try is:
jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

Categories

Resources