0

I'm working on a little script that will disable a form field if certain radio button are ticked or if the input filed has characters to disable the radio buttons

So what I'm wanting my code to do is when the User enters the text field and adds at least one character of any type to disable the radio buttons and if that field is cleared to re-enable the radio buttons

For some reason when I'm doing either or, my "Enabled" alert keeps showing and the radio buttons aren't being disabled

to get the alert to pop, need to click outside of the input field, I would like this to be a mouseout if possible but I can work on that later

If the value is entered within the form directly, the radio buttons are disabled but I can't get them enabled once the filed is cleared

Steps: Enter text in text field, if value isn't set in the form. Radio buttons stay disabled

Enter Value within the form, the text buttons stay disabled when the text field is cleared

Working Parts: If radio btn "Yes" is ticked display "test" string and disable text field If Radio btn "No" is ticked then enable text field

jQuery version in use: 1.9

Below is my JavaScript and below that is the HTML

Script:

$(function() {

    var tlHeader = 'Test';

    var f2 = $('#field_2').val();

    // This function controls inpput box toggling on/off radio buttons
    $( '#field_2' ).change(function() {
        if(f2.length != 0) {
            alert( "Disabled" )
            $("input[name=toggle]").prop('disabled', true)
        } else if(f2.length == 0) {
            alert( "Enabled" ) 
            $("input[name=toggle]").removeProp('disabled')
        };
    }); 

   window.invalidate_input = function() {
      // This function controls radio btn actions
        if ($('input[name=toggle]:checked').val() == "Yes") {
            $('#field_2').attr('disabled', 'disabled'),
            $('#thgtLdr').html( tlHeader );
            $('#thgtLdr').not("No").show();

        } else if ($('input[name=toggle]:checked').val() == "No") {
            $('#field_2').removeAttr('disabled'),
            $('#thgtLdr').not("Yes").hide();
        }
   };


    $("input[name=toggle]").change(invalidate_input);

    invalidate_input();
});
</script>

HTML:

      <body>

<div id=rdTest>
    <div class="inputField">
        <label>Focal Image:</label>
        <input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
    </div> <!-- End input field -->


  <div class="radioGroup">
    <label>Test Page:</label>
        <input type='radio' name='toggle' value='Yes' id="tglyes"/>Yes
        <input type='radio' name='toggle' value='No' id="tglno"/>No
  </div> 

<div id="thgtLdr">

</div>

</div>  



</body> 
popeye1716
  • 1
  • 1
  • 1

3 Answers3

0

Your use case isnt entirely clear but I'll show you how to achieve the basic goal.

First, I would avoid the mouse events and use keyup with a timer so that my function is only called when the user stops typing and not after each typed letter. Then it's just a mater of checking the text and acting to enable or disable the elements. Here is an example:

    var keyupDelay = (function(){
        var timer = 0;
        return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
    })();
    
    $('#field_2').keyup(function() {
        var $this=$(this);
        keyupDelay(function(){
            var val=$this.val();
            console.log(val);
            if(val=='') $('#tglyes, #tglno').prop('disabled',true);
            else $('#tglyes, #tglno').prop('disabled',false);
        }, 400 ); // triggered after user stops typing for .4 seconds, adjust value as needed
    });
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=rdTest>
    <div class="inputField">
      <label>Focal Image:</label>
      <input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
    </div>
    <!-- End input field -->
    <div class="radioGroup">
      <label>Test Page:</label>
      <input type='radio' name='toggle' value='Yes' id="tglyes" disabled="true"/>Yes
      <input type='radio' name='toggle' value='No' id="tglno"  disabled="true"/>No
    </div>

    <div id="thgtLdr">
    </div>
  </div>
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
0

You can simplify your code in many ways.

The keyup event will be triggered every time the user releases a key on the text field. Inside the callback, you can get the value of the text field with this.value. From experience, it is best to use .prop() method when toggling certain input-related attributes like disabled and checked. You can enable/disable these attributes using booleans.

// cache the elements to avoid having retrieve the same elements many times
var $textbox = $('#field_2'), 
    $radios = $('input[name=toggle]'), 
    $div = $('#thgtLdr');

// everytime user presses a key...
$textbox.on('keyup', function() {
    // check if a value was entered or not
    // if so, disabled the radio buttons; otherwise enable the radio buttons
    $radios.prop('disabled', this.value);
});

// when radio buttons change...
$radios.on('change', function () {
    // check if value is Yes or No
    if (this.value === 'Yes') {
        $textbox.prop('disabled', true);
        $div.text(this.value);
    } else {
        $textbox.prop('disabled', false);
        $div.empty();             
    }
});
<div id=rdTest>
<div class="inputField">
    <label>Focal Image:</label>
    <input name="FocalImage" type="text" id="field_2" class="textbox" value="">
</div>
<div class="radioGroup">
    <label>Test Page:</label>
    <input type="radio" name="toggle" value="Yes" id="tglyes">Yes
    <input type="radio" name="toggle" value='No' id="tglno">No
</div>
<div id="thgtLdr"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script> // place code here </script>

Also, get into the habit of caching your jQuery objects.

Community
  • 1
  • 1
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • In the above window it's functioning exactly how I would want it. But when I bring it into Dreamweaver for further testing and development, It doesn't seem to be working. I'm placing my call to jquery 1.9.0 and placing the script within the head tag. But, When I place the jQuery library in the body tag I get this error in the console. ReferenceError: $ is not defined var $textbox = $('#field_2'). with an arrow pointing to $textbox Am I missing something? – popeye1716 May 27 '16 at 16:17
  • I am not entirely sure how Dreamweaver works (and I wouldn't recommend that you use Dreamweaver for testing as it has numerous problems and is not even a real browser). You probably have the order wrong. If you are going to put the jQuery script inside the body, then place it at the end (as shown in my edit). Then, if you are also placing my JS code inside the body, place it after the jQuery script. – Mikey May 27 '16 at 17:02
  • Thank you very much for time with this, It works when putting at the end of the HTML. With the same order shouldn't it work if I placed both scripts in teh head section? 1st jQuery version then Code – popeye1716 May 27 '16 at 20:50
  • If you place both scripts in the `head`, then you need to wrap my script with `$(document).ready(function() { ... }` or shorter `$(function() { ... }` as shown [here](https://learn.jquery.com/about-jquery/how-jquery-works/#launching-code-on-document-ready). This is to ensure that the DOM is ready. If you choose to place both scripts at the end of the `body` then the DOM will be ready by the time those two scripts get executed. (Feel free to mark the answer as correct.) – Mikey May 28 '16 at 00:50
  • Thank you for the info Mikey, I can't mark as the correct answer as I don't have enough reputation. I'll come back once I get to that point – popeye1716 Jun 13 '16 at 15:22
0

Try this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).on('click','.choice',function(){
    if($(this).val() == 'yes')
    {
       $('.textfield').prop('disabled',true);
       $('#string').html('Test Welcome');
    }
    else
    {
       $('.textfield').prop('disabled',false);
       $('#string').html('');
    }
});
$(document).on('keyup','.textfield',function(){
    if($(this).val().length > 0)
    {
       $('.choice').each(function()
       {
          if($(this).is(':checked'))
          {
             $(this).attr('checked',false);  
          }
          $(this).prop('disabled',true);
       });
    }
    else
    {
       $('.choice').prop('disabled',false);
    }
});
});
</script>
<body>
<form>
    <input type="text" class="textfield" placeholder="enter text"/>
    Yes<input type="radio" name="choice" class="choice" value="yes" />
    No<input type="radio" name="choice" class="choice" value="no" />
    <p id="string" ></p>
</form>
</body>
Vijay Wilson
  • 516
  • 7
  • 21