0

I want to get the user's selected option value as a javaScript alert. But my alert is not working.

Here is my HTML code.

<select id="formats_id" name="aformats" >
    <option value="<?php echo $jrowa2['formats']; ?>" onchange="showshowFormat(this.value)" ><?php echo $jrowa2['formats']; ?></option>
        <?php foreach($formats3 as $v3){  ?>
            <?php if($v3 !== $jrowa2['formats']) { ?>
                <option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
            <?php } ?>
        <?php } ?>
</select>

Here is my javaScript code.

function showshowFormat(){
    var $this = $(this); //  assign $(this) to $this
    var formats_value = $this.val();
    alert(formats_value);
}

5 Answers 5

2

Try onchange with select:

Pure JS

var showFormat = function(dd) {
  var opt = dd.options; //array of option of the select tag
  var i = dd.selectedIndex; // index of selected option
  alert(opt[i].value);
};
<select id="formats_id" name="aformats" onchange='showFormat(this);'>
  <option>Text</option>
  <option>PDF</option>
  <option>Excel</option>
</select>

JQuery

$(function() {
  $('#formats_id').on('change', function() {
    alert($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="formats_id" name="aformats">
  <option>Text</option>
  <option>PDF</option>
  <option>Excel</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

0

try this

function showshowFormat(){
    var $this = $('#formats_id'); //  assign $('#formats_id') to $this
    var formats_value = $this.val();
    alert(formats_value);
}

Comments

0

Use this :

function showshowFormat(){
    var Getvalue= $('#formats_id'); 
    var formats_value = Getvalue.val();
    alert(formats_value);
}

Comments

0

First you need to load jQuery in your html, then try below codes:

<script>
$('#formats_id').change() {
    var $this = $(this); //  assign $(this) to $this
    var formats_value = $this.val();
    alert(formats_value);
}
</script>

Comments

0

try this..

$('#formats_id').on('change', function() {
  alert( this.value ); // or $(this).val()
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.