Remn
Remn

Reputation: 261

Get the string, but not the value from dropdown list option select

I have two select box, and one hidden text box

<select name="name" id="name" class="form-control input-sm">
  <option value="">- Choose a Name -</option>
 <?php foreach($name as $n) { ?>
  <option value="<?php echo $n->id_name;?>"><?php echo $n->name;?></option>
 <?php } ?>
</select>

<select name="status" id="status" class="form-control input-sm">
  <option value="">- Choose a Status -</option>
 <?php foreach($status as $s) { ?>
  <option value="<?php echo $s->id_status;?>"><?php echo $s->name;?></option>
 <?php } ?>
</select>

<input type="hidden" id="message" name="message" value="">

What I know is the script like this

function inputKelurahan()
 { var name = document.getElementById("name");
   var status = document.getElementById("status");
   document.getElementById("message").defaultValue = name.value + status.value;
 }

Of course, the message would be $id_name + $id_status. How to concate $name + $status?

Thanks in advance,

Upvotes: 1

Views: 1915

Answers (2)

smoksnes
smoksnes

Reputation: 10871

It sounds as you want the text inside the selected option. Then you can first get the selectedIndex, and then the innerHTML for the option.

Below is a simple snippet, with parts of your code.

function inputKelurahan()
{ 
  var name = document.getElementById("name");
  var status = document.getElementById("status");
  var nameInnerHtml = name.options[name.selectedIndex].textContent; // using textContent as mentioned by james.brndwgn in comments.
  var statusInnerHtml = status.options[status.selectedIndex].textContent;
  alert("Name is: " + nameInnerHtml + ". Status is: " + statusInnerHtml);  
}
<select name="name" id="name" class="form-control input-sm">
  <option value="">- Choose a Name -</option>
  <option value="Value1">Name 1</option>
  <option value="Value2">Name 2</option>
  <option value="Value3">Name 3</option>
</select>

<select name="status" id="status" class="form-control input-sm">
  <option value="">- Choose a Status -</option>
  <option value="StatusValue1">Status 1</option>
  <option value="StatusValue2">Status 2</option>
  <option value="StatusValue3">Status 3</option>
</select>

<button onclick="inputKelurahan()">Click me!</button>

Upvotes: 2

obwan02
obwan02

Reputation: 113

function inputKelurahan()
 { var name = document.getElementById("name");
   var status = document.getElementById("status");
   document.getElementById("message").value = name.selectedIndex.value + status.selectedIndex.value;
 }

Upvotes: 0

Related Questions