shubham jha shubham jha - 2 months ago 11
HTML Question

jQuery and PHP to update Select Box value in Text field

I know this question has been asked a lot of times in several other ways but none of them helped me. So, I have formatted it in my own words.

Supppose I have a select box like this:

<select name="something">
<option value="1"><?php echo $value1; ?> for <?php echo $value2; ?>
</select>
<input type="text" name="sometext" value="">


I want to have the
<?php echo $value1; ?>
in the text field updated live on change of the select box option. To be clear, I DO NOT want the
value="1"
in the text field and I need to have that
value="1"
there for some reason and I cannot replace it with
value="<?php echo $value1; ?>"
. I strictly want the inside value
<?php echo $value1; ?>
to be replaced in the text field. But I do not know how I can achieve it. Please help me experts. For live changing jQuery preferred.

SCC SCC
Answer

Try below code:

<select name="something">
    <option value="1" data="<?php echo $value1; ?>"><?php echo $value1; ?> for <?php echo $value2; ?></option>
</select>
<input type="text" name="sometext" value="">

See below working HTML

jQuery(document).ready(function($){
  $('#something').change(function(){
    $('#sometext').val($(this).find(':selected').attr('data'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="something" id="something">
    <option value="1" data="value1">value1 form value01</option>
    <option value="1" data="value2">value2 form value02</option>
    <option value="1" data="value3">value3 form value03</option>
    <option value="1" data="value4">value4 form value04</option>
</select>
<input type="text" name="sometext" id="sometext" value="">

Comments