I have a problem returning a string where the value "cheese" is replaced with "jam". My scenario is first starting with I default values of cheese and mushrooms to be selected. If I want to select Cheese,Tomatoes,Mushrooms, console log I need the value "cheese" is replaced with "jam", and the console log result should be "jam,tomatoes,mushrooms". When I clicked the check value button, the errors message show me str.replace is not a function
in the console log.
Below is my sample coding:
$('#select_multiple').multiselect()
var data="cheese,mushrooms";
var dataarray=data.split(",");
$("#select_multiple").val(dataarray);
$("#select_multiple").multiselect("refresh");
function check_value(){
var str = $('#select_multiple').val();
var abc = str.replace("cheese", "jam");
console.log(abc);
}
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" />
</head>
<body>
<select id="select_multiple" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
<button onclick="check_value();">Check Value</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
</body>
</html>
I have tried to alert variable str
to check values, it got values. Just cannot console log the values. Hope someone can guide me on how to solve this problem. Thanks.
2
Answers
That is because you are getting str as an array. You need to use for loop to replace the string that you want. see below example
that’s because str is an array. that’s why you still have to iterate the variable…