Reputation: 143
Hi I need to change the hardcoded url in the value property of input attribute dynamically based on a dropdown selected.
Following is the code I tried but not working. I am new to Javascript. Please help
var returnValue = checkDropDown();
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
function checkDropDown() {
const platForm = $('#platform-select').val();
console.log("platform select"+platForm);
return platForm;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<label for="platform">Choose from dropdown :</label>
<select name="platform" id="platform-select" onchange="togglePlatformOptions()">
<option value="DropDown1" >foo</option>
<option value="DropDown2" selected>bar</option>
</select>
<input type="text" id="URLField" value="myValue"/>
</body>
Upvotes: 1
Views: 607
Reputation: 121
As you already have a function defined on change event on dropdown(called togglePlatformOptions) you can just use it. Just add to this function your functionality. Like below
function togglePlatformOptions(){
//you old code if it exists already
var returnValue = document.getElementById('platform-select').value;
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
}
UPDATE: Seems you have a function checkDropDown, then add everything you have inside
function togglePlatformOptions(){
var returnValue = checkDropDown();
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
}
UPDATE #2: To have it on initialization just call it
function togglePlatformOptions(){
var returnValue = checkDropDown();
var myValue = returnValue === "DropDown1" ? "http://url1/..." : "http://url2..";
var input = document.getElementById('URLField');
input.value = myValue;
}
// below call added
togglePlatformOptions();
Upvotes: 2