shine shine - 4 years ago 66
Javascript Question

How to allow user to add only one value at a time?

I need to allow user to enter value at only one box at a time.
For eg: if user enter months the days field should not allow him to enter value.
Can I disable the other field if user enter value in any of them ?

Also it only takes numbers.

dad

Here is my html

<td class="ctext" width="13%"> Reset Frequency in Months/Days
</td>
<td class="ctext" style="display:inline-block">
<label for="frMnth" style="display:block">Month</label>
<input type="text" class="textfield" value="" id="frMnth" name="frMnth" onkeypress="return isNumber(event)" />
<label for="frDays" style="display:block">Days</label>
<input type="text" class="textfield" value="" id="frDays" name="frDays" onkeypress="return isNumber(event)" />
</td>


And this is script to type number only using Onkeypress.

function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;}


Can I disable the field using Onkeypress ?

Answer Source

Try this: http://jsfiddle.net/lotusgodkk/GCu2D/1011/

HTML:

<td class="ctext" width="13%"> Reset Frequency in Months/Days</td>
<td class="ctext" style="display:inline-block">
    <label for="frMnth" style="display:block">Month</label>
    <input type="text" class="textfield" value="" id="frMnth" name="frMnth" />
    <label for="frDays" style="display:block">Days</label>
    <input type="text" class="textfield" value="" id="frDays" name="frDays" />
</td>

JS:

$(document).ready(function() {
    $(document).on("blur", ".textfield", function() {
        var ele = $(this);
        if (ele.val()) {

            if (isNaN(ele.val())) {
                alert("Only numbers please");
                return false;
            }
            $(".textfield").not(this).attr("disabled", "disabled");
        } else {
            $(".textfield").removeAttr("disabled");
        }
    });
});

Alternative solution without JS

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/1012/

HTML:

<td class="ctext" width="13%"> Reset Frequency in Months/Days</td>
<td class="ctext" style="display:inline-block">
    <label for="frMnth" style="display:block">Month/Days</label>
    <input type="number" class="textfield" value="" id="frMnth" name="frMnth" />
    <select>
        <option value="month">Month</option>
        <option value="days">Days</option>
    </select>
</td>

Change the input type to number. Let browser take care of the number onlyrequirement. Of course you can add JS for further validations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download