Reputation: 2248
I have a dropdown list and a textbox. I am trying to replace the dropdown list selected value to some value by changing the text in textbox.
Here is my code:
<select class="form-control Series-1 valid" name="CRMFields" id="CRMFields">
<option>None</option>
<optgroup label="Lead Information"></optgroup>
<option value="First Name^Lead ID^">Lead ID</option>
<option value="First Name^First Name^" selected="">First Name</option>
<option value="First Name^Last Name^">Last Name</option>
</select>
<input class="defaultValue" data-target-class="Series-1" id="DefaultValue" name="DefaultValue" type="text" value="">
JQuery:
<script type="text/javascript">
$(document).ready(function () {
$(".defaultValue").change(function () {
var thisval = $(this).val();
var targetclass = $(this).attr("data-target-class");
var CRMFiledValue = $("." + targetclass).val();
var arr = CRMFiledValue.split('^');
var left = arr[0];
var middle = arr[1];
var last = thisval;
var replaceText = left + "^" + middle + "^" + last;
alert(replaceText);
alert($("." + targetclass).prop("value", replaceText));
alert($("." + targetclass).val());
});
});
</script>
But above code showing me [object Object] and null on the alert box instead of concatenated value.
I want to replace the selected item of value to some value on Change event of text box.
I appreciate your help in advance.
Upvotes: 1
Views: 1592
Reputation: 24638
You should change:
$("." + targetclass).prop("value", replaceText);
To:
$("." + targetclass + ' option:selected').val(replaceText);
And always bear in mind that this operation does not return a scalar value and will therefore return [Object Object] to alert( ... )
. A better debug function would be console.log( .... )
:
Upvotes: 0
Reputation: 1483
Part of the problem is that you are changing the value of every single option whenever someone changes the value of the input box.
so I added + option:selected
to the selector of the var CRMFiledValue
. I assume this is what you were going for because you probably didn't want every field to have FirstName^FirstName^thisval
as it's value. The below code was tested and worked according to how your HTML/other javascript was set up
$(document).ready(function () {
$(".defaultValue").change(function () {
var thisval = $(this).val();
var targetclass = $(this).attr("data-target-class");
var CRMFiledValue = $("." + targetclass + ' option:selected').val();
var arr = CRMFiledValue.split('^');
var left = arr[0];
var middle = arr[1];
var last = thisval;
var replaceText = left + "^" + middle + "^" + last;
$("." + targetclass + ' option:selected').prop("value", replaceText);
});
});
Upvotes: 2