swan swan - 18 days ago 5
jQuery Question

How to completely empty input text even when empty by default

I have several inputs, some are provided with default value, some are empty, and filled up by a select value dynamically.

When I do a select, the value of select box is inserted into the input text.

The problem is when textfield is empty, and then later filled up with the select value, and then using a reset/clear button, the input text is not emptied, yet it is still holding the dynamic inserted value:

Inputs:

<input type="text" value="" name="yahoo">
<input type="text" value="some default value" name="google">
<button class="button clear" type="button" accesskey="x">Clear</button>


Jquery:

$('button.clear').click(function () {
$('input').val(''); // this clears google, but not yahoo
});


And some select box input the values dynamically to textfields.
Any idea to completely empty the textfield?
Thanks

Steps:


  1. I do change a select box

  2. The value of select is inserted into textfield. All is well

  3. The problem is when default is empty, the clear button do not empty the textfield (which is dynamically filled up)



I will clarify my question with simplified code:

$('select').swicthClass();

$.fn.swicthClass = function (options) {
// .............
};

var src = 'some-value-from-select-box'; // hence good, bad etc
$('body.bad').find('input[name="yahoo"]').val(src);



<select>
<option selected="selected" value="good">Good</option>
<option value="bad">Bad</option>
<option value="worse">Worse</option>
<option value="damn">Damn</option>
</select>

Answer

You might want to try this

$('button.clear').click(function () {
  $('input').val('');
});

$("select").on("change", function() {
  var src = 'good';
  $('[name=yahoo]').val(src); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" value="" name="yahoo" >
<input type="text" value="some default value" name="google">
<button class="button clear" type="button" accesskey="x">Clear</button>

<select>
  <option selected="selected" value="good">Good</option>
  <option value="bad">Bad</option>
  <option value="worse">Worse</option>
  <option value="damn">Damn</option>
</select>