kpatel35
kpatel35

Reputation: 1

Javascript Represent an integer as any string

I need help representing an integer as any string of my choice (not just the actual string representation of the integer).

Context- I have a dropdown box on a web app consisting of numbers placed into an array [10, 5, 0, -5, -10]. On the web application I need the 0 to appear as the string "Select", but still maintain the functionality of the int 0. There may be an HTML or CSS solution to this if it is not possible in JavaScript. Thank you.

Upvotes: 0

Views: 75

Answers (3)

Alvaro Silvino
Alvaro Silvino

Reputation: 9743

Simple as that:

var selectValues = [10, 5, 0, -5, -10];
$.each(selectValues, function(key, value) {   
     if(value==0){
       $('#cars')
         .append($("<option ></option>")
         .attr("value",value)
         .text("Select")); 
     }else{
       $('#cars')
         .append($("<option ></option>")
         .attr("value",value)
         .text(value)); 
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="demo_form.asp">
  <select id="cars" name="cars">
    
  </select>
  <input type="submit" value="Submit">
</form>

Upvotes: 0

arcyqwerty
arcyqwerty

Reputation: 10685

If you have a dropdown (i.e. select element), the value attribute of the option elements are independent of the text displayed to the user.

You can have an

<option value="value that you want to have in code">
    Text that your user should see
</option>`

If the select needs to be populated from an array, then you can use JavaScript to create DOM elements and add them to the corresponding select node.

HTML

<select id="selectbox"></select>

JS

array.forEach(function(e) {
    var option = document.createElement('option');
    option.value = e;
    option.textContent = e ? e : 'Select';
    document.getElementById('selectbox').appendChild(option);
});

Should generate

<select>
  <option value="10">10></option>
  <option value="5">5></option>
  <option value="0">Select</option>
  <option value="-5">-5></option>
  <option value="-10">-10></option>
</select>

Upvotes: 1

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

You can use the value property of the options:

<select id="my-select">
   <option value="0">Select</option>
   <option value="10">10</option>
   <option value="-5">-5</option>
</select>

Javascript to get current value:

var ele = document.getElementById('my-select');
var myValue = ele.options[ele.selectedIndex].value;

Upvotes: 0

Related Questions