简体   繁体   中英

how to use JavaScript for reseting text field value?

I have following code:

<div class="form-group">
    <?= $form->labelEx($model, 'membership', array('class' => 'col-xs-12 col-sm-4 control-label')) ?>
    <div class="col-xs-12 col-sm-3">
        <?= $form->dropDownList($model, 'membership', array(Yii::t('member', 'Yes'), Yii::t('member', 'MO')), array(
                'class' => 'form-control',)); ?>

    </div>
    <?= $form->error($model, 'membership') ?>
</div>

and

<div class="col-xs-12 col-sm-3">
    <?= $form->textField($model, 'question', array('class' => 'form-control dotted')) ?>
    <?= $form->error($model, 'question') ?>
</div>

I need to develop a JavaScript file which resets textField, when user chooses 'NO' option from the drop down menu. How can I do it?

Try this:

// for Id selector
document.getElementById('element_id').value = '';

// for class selector
document.getElementsByClassName("element_class").value = '';

you can create javascript function like

function myFunction(val) { 
    if(val=='NO') 
    { 
        document.getElementById('element_id').value = ''; 
    } 
} 

and call it like this: <select onchange="myFunction(this.value)">

Try JS/JQuery . apply onchange function in dropdown . In function check selected value and if it is NO then empty text field by using id

below text_field_id is id of your text field

<?= $form->dropDownList($model, 'membership', array(Yii::t('member', 'Yes'), Yii::t('member', 'MO')), array(
                'class' => 'form-control','onchange'=>'validate(this.value)')); ?>


<script type="text/javascript">
        function validate(value)
        {
            if(value == 'NO') {
           document.getElementById('text_field_id').value = '';

          }
        }
    </script>

First of all add onchange function in <select> as:

<?=$form->dropDownList($model, 'membership', array(Yii::t('member', 'Yes'), Yii::t('member', 'MO')), 
array('class' => 'form-control','onchange'=>'getAlert(this.value)')); ?>

Than in javascript:

<script type="text/javascript">
  function getAlert(value){
    if(value == 'No'){
      document.getElementsByName("membership").value = '';
    }
  }
</script>

YII Reference

$( "selector_class_or_id" ).change(function() {

var selected_value = $(this).val();

if(selected_value === 'NO'){
   $("textField_class_or_id").val('');
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM