user5358888
user5358888

Reputation: 207

Select tag not able to collect all values in HTML

I have an HTML form where select tag is used for the inputs, with 4 options where in the last one is named as other.When selected other a text field comes and the input can be given:

HTML form:

<html>
<head>
    <script type="text/javascript">
    $('select').on('change', function(){
    if($(this).val()=='Other:'){
    $('#other').show().focus();
    }else{
    $('#other').val('').hide();
    }
    })
    </script>
</head>
<body>
<tr>
  <td>
    <label>Options : </label>
  </td>
  <td>
    <select name="Options">
    <option value="Option-1">Option-1</option>
    <option value="Option-2">Option-2</option>
    <option value="Option-3">Option-3</option>
    <option value="Other:">Other</option>
    </select>
    <input type="text" id="other" style="display:none" name="other"  style="display:none"/>
  </td>
</tr>
</body>
</html>

While inserting in the DB am only able to insert the value added in the text field. Where in the option 1,2,3 are not getting collected and inserted in DB.

PHP code to insert the value in mysql DB:

<?php
$link = mysqli_connect("localhost", "root", "", "database");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$Options = mysqli_real_escape_string($link, $_POST['Options'], $_POST['other']);
$sql = "INSERT INTO Table (Options) VALUES ('$Options');
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>

i want to collect the option which ever is selected and inserted in DB. Currently am only able to insert the other option where the data will be entered through text field.

Thanks in advance.

Upvotes: 0

Views: 184

Answers (1)

Philipp
Philipp

Reputation: 2796

Use if else to switch between the values depending on that input has been given via the selectlist.

if($_POST["Options"] !== "Other:"){
    $Options = mysqli_real_escape_string($link, $_POST['Options']);
}else{
    $Options = mysqli_real_escape_string($link, $_POST['other']);
}
$sql = "INSERT INTO Table (Options) VALUES ('$Options')";
// ...

Upvotes: 1

Related Questions