0

setDefaultValue function is called when operation is changed on the page so when one operation is done i want to set dropDown value to JavaScript using Jquery thats not happening with below code , what is implemented wrong ?

dropdown text should say JavaScript

main.html

<div style="text-align: right;margin: 5px;margin-left: 45%">
    <select name="dropDownSelect"  onchange="handleDropDown(this.value)">
        <option value="JS" selected="selected">JavaScript</option>
        <option value="TS">TypeScript</option>
    </select>
</div>

main.js

function setDefaultValue () {
    $("#dropDownSelect").val('JavaScript');
}
11
  • How do you call setDefaultValue? Any errors in your console? Commented Sep 23, 2019 at 14:17
  • Do you want to add this option as hack in additon to JS and TS? or you mean that JS? Commented Sep 23, 2019 at 14:17
  • @j08691 no error in console , setDefaultValue is being called in another method and when i set break point it does go to the line in setDefaultValue but Values stays to the last selected that was TypeScript Commented Sep 23, 2019 at 14:18
  • 2
    The "value" is JS and not JavaScript Commented Sep 23, 2019 at 14:20
  • 1
    Where do you have an element with the ID dropDownSelect for $("#dropDownSelect") to match? Commented Sep 23, 2019 at 14:22

2 Answers 2

1

Try to do this like

<select name="myselect" id="myselect">
    <option value="1">Value one</option>
    <option value="2">Value two</option>
    <option value="3">Value three</option>
</select>

$("#myselect option[value=2]").attr('selected', 'selected');

Or

<script type="text/javascript"> 
  function addOption() { 
    optionText = 'Value two'; 
    optionValue = 'Value two'; 

    $('#select1').append(`<option value="${optionValue}"> 
     ${optionText} 
     </option>`); 
  } 
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Try this, if you just need to change the selected value of the drop down:

$("select[name='dropDownSelect'] option[value='TS']").attr('selected','selected');

If there is an event bind on the drop down change, or any function is called, try this:

$("select[name='dropDownSelect'] option[value='TS']").attr('selected','selected');
$("select[name='dropDownSelect']").trigger('change');

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.