I have a bit of JQuery that I am trying to use to detect if the value that is in a data list select box is actually in the list, here is what i have.
<div class='form-row'>
<div class='col-xs-12 form-group required' style="margin-top: -2px; margin-bottom: 0px;">
<h2>
<label class='control-label' style="font-size: 20px;">
Product code
</label>
</h2>
<input required id="ItemSelect" list=jobs style='font-size:21px;height: 40px;' class='form-control' name="Code">
<datalist id="jobs">
<?php
foreach ($this->Products as $a) {
$inputValue = " " . htmlentities($a["Code"] . " | " . $a["Name"]) . " ";
echo '<option>' . $inputValue;
}
?>
</datalist>
</div>
$('#submit').on('click', function (e) {
var datalistval = $('#ItemSelect').val();
console.log(datalistval);
console.log($("#ItemSelect option[value='" + datalistval + "']").length)
if ($("#ItemSelect option[value='" + datalistval + "']").val() === undefined) {
console.log("not there");
} else {
console.log(" there");
}
});
currently with this if i enter a value that is not in the list it comes back as no there, but it also comes back as not there if i do select one out of the list.
Here out the outputs of the console.logs
console.log(datalistval); // X01A172 | Sub Assembly 2
console.log($("#ItemSelect option[value='" + datalistval + "']").length) // 0
not there
Related
I am trying to create an additional form text field on click of a button which wotrtks fine, my only problem is that the select option is blank and when I inspect element I see that NAN is added to it.
Here is the design for the dynamic form elements container
<div class="col-sm-6" id="prescription-container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" class="form-control search-select">
<?php echo $drug_drop_down; ?>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Comment</label>
<div class="phone-icon">
<input type="text" class="form-control" name="diagnosis">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<a href="#" id="add_prescription" class="btn btn-warning"><i class="fa fa-plus"></i>Add
prescription</a>
</div>
</div>
This is how I have implemented the onclick listener for the add prescription button
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
var result="<option value=''>Select Drug<option>";
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
if (data.length > 0) {
$.each(data, function(i, item) {
result += "<option value='" + data.id + "'>"+data.name+"<option>";
})
} else{
result += "<option value='" + data.id + "'>"+data.name+"<option>";
}
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ result +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Finally this is the controller sending back data
function () {
$drugs = Medicine::get();
return response()->json( $drugs);
}
Now my problem is that when i alert(data) I get [object Object],[object Object]. This made me modify the controller as follows
function () {
$drugs = Medicine::get();
$drug_drop_down = "<option>Select drug</option>";
foreach($drugs as $drug){
$drug_drop_down .="<option value='".$drug->id."'>$drug->name</option>";
}
return response()->json( $drug_drop_down);
}
and the onclick listener to
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ data +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Now if I alert(data) I get <option>Select drug</option><option value='1'>Quinine</option><option value='2'>Malariaquine</option> but the select is still being added without options and the following appear on inspect element for the added filed
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" '="" class="form-control">NaN</select>
</div>
</div>
</div>
What could I be doing wrong here?
After some searching just realized that the second way was supposed to work except that this + + data + "</select>" + means I am using + as an addition operator and not a concatenator, changing it to + data + "</select>" + solved my problem. I do not still understand what the issue could have been with the first approach
I am confused how to populate my dropdown that adds on button click with database values . I used jQuery to do the adding function of dropdown on button click. but it seems like i cant populate the options of the select tag inside my jQuery with database values. Please help me out...
This is my php page
<?php include("connect.php");
$smt = $conn->prepare('select CompanyName From Company');
$smt->execute();
$data = $smt->fetchAll();
?>
<div class="form-group" id='TextBoxesGroup'>
<label for="layer" class="col-sm-3 control-label">Layer</label>
<div id="TextBoxDiv1" class="col-sm-6">
<select class="form-control" id='textbox1' name="company" placeholder="Company" >
<?php foreach ($data as $row): ?>
<option><?=$row["CompanyName"]?></option>
<?php endforeach ?>
</select>
</div><hr/>
</div>
<div class="form-group" >
<div class="col-md-9 text-right">
<input type='button' class="btn btn-default" value='Add +' id='addButton'>
</div>
</div>
The jQuery code used to add dropdown on button click is:
EDIT:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 Layers allowed");
return false;
}
var companies = [<?php echo "'".join("','",$data)."'";?>];
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div class="form-group" id="TextBoxesGroup"><label class="col-sm-3 control-label">Layer '+ counter + ' : </label>' +' <div id="TextBoxDiv1" class="col-sm-6"><select class="form-control" name="textbox' + counter + '" id="textbox' + counter + '" name="company" placeholder="Company">');
$.each(companies, function(key, value){
newTextBoxDiv.append('<option>'+value+'</option>');
});
newTextBoxDiv.append('</select> </div></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
</script>
But the output shows like this:
Thanks
Well, you need to echo out the value of $row['companyName'] (the one inside your foreach loop)
Another implementation would be... say you have an array of values in your PHP.
$data = array("company A", "company B", "company C");
And the javascript...
<script>
var companies = [ <?php echo "'". join("','", $data) . "'";?> ];
//This generates : ['company A', 'company B', 'company c'];
function insertOptions()
{
$.each(companies, function(key, value){
$("#IDofSelectTag").append("<option>"+value+"</option>");
});
}
</script>
I have a problem.
here is my php & HTML:
<?php
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$sub_lapangan."',1,$row->IDLapangan);");
}
?>
<HTML><BODY>
<div class="row">
<div class="form-group" id="sub_lapangan">
<div class="col-lg-3"><label>Nama Sub-Lapangan :</label></div>
<div class="col-lg-2">
<input type="text" name="sub_lapangan" class="form-control" required>
</div>
<div class="col-lg-1">
<a onclick="tambahSubBaru()" class ="btn btn-info"> <i class="fa fa-plus"></i></a>
</div>
</div>
</div>
<div id="sembunyisub">
</div>
</BODY></HTML>
Here is my script:
var count = 0;
function tambahSubBaru() {
count += 1;
if (count > 15) {
alert("Maksimal Untuk Tambah Sub Lapangan adalah 15 Sub Lapangan");
}
else {
$('#sembunyisub').append(
'<div class="row" id="barisbarusub' + count + '">'
+ '<div class="form-group">'
+ '<div class="col-lg-3">'
+ '</div>'
+ '<div class="col-lg-2">'
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan" required>'
+ '</div>'
+ '<div class="col-lg-1">'
+ '<a class ="btn btn-warning" onclick="hapusSub(' + count + ')"> <i class="fa fa-trash"></i></a>'
+ '</div>'
+ '</div>'
+ '</div>'
);
}
}
function hapusSub(row) {
$('#barisbarusub' + row).remove();
}
Here is the pic:
So the scenario is, when i click the "plus" button, it will show up the second textbox. I want to insert them into database. but when i try to insert, the SECOND textbox is succedded to insert in database. but the FIRST textbox doesn't insert to database.
How can i insert the FIRST textbox?
to show up the second textbox, i use .append in javascript.
help me please. I aprreciated the answer. many thank you. :)
You have to loop through your fields in PHP. Therefore you have to create an Array-input-element with [] after the name.
HTML:
<input type="text" name="sub_lapangan[]" class="form-control" required> <!-- Add [] to your field name for creating an Array-->
JS:
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan[]" required>' //The same in you dynamic input field
PHP: Loop through you fields (Array)
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$fields = $_POST['sub_lapangan']; //Your Array
foreach($fields as $field => $value) {
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$value."',1,$row->IDLapangan);");
}
}
Try this:
'INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES("'.$sub_lapangan.'","1","'.$row->IDLapangan.'")'
i have a form that has an input field that uses a datalist, what i want to do is when something is selected from that field, update another input field with what was selected, here is what i have so far
<div class='form-row'>
<div class='col-xs-12 form-group required'>
<h2><label class='control-label'>Product code</label></h2>
<input id="ItemSelect" type=text list=jobs style='font-size:21px;height: 40px;'
class='form-control'
name="Code">
<datalist id=jobs>
<?php
foreach ($this->Products as $a) {
echo '<option value=' . $a["Code"] . '>' . $a["Code"] . " - " . $a["Name"] . ' </option>';
}
?>
</datalist>
</div>
<div class='col-xs-12 form-group required'>
<input id="Placeholder" readonly class='form-control'
placeholder="Prodcut Descirption">
</div>
<script>
$("#ItemSelect")
.change(function () {
var str = "";
$("datalist option:selected").each(function () {
str += $(this).text() + " ";
});
$("#Placeholder").attr("placeholder", str).val("").focus().blur();
})
.change();
</script>
this kind of works, it is selecting the right input field to detect the change, however it's not putting the value in. if i change
$("datalist option:selected")
to
$("select option:selected")
it does put the value of all the other select fields in there any ideas?
There is no such thing as option:selected in datalists.
You can get the selected value by looking at what's currently in the input instead:
$("#ItemSelect").change(function() {
var str = $(this).val() + " ";
$("#Placeholder").attr("placeholder", str).val("").focus().blur();
});
If you only want to do this when the input value is actually present in the datalist:
$("#ItemSelect").change(function() {
var str = $(this).val() + " ";.
$('datalist option').each(function() {
if($(this).text() === str) {
$("#Placeholder").attr("placeholder", str).val("").focus().blur();
}
});
});
<datalist id=jobs>
should change datalist tag to select tag
<select id=jobs>
once you change that the below statement will work
$("select option:selected")
i am creating a dynamic dropdowns based on a scenario i need to. i am wondering how it possible to keep the states of those added drop downs dynamically when a page is loading after submit button is clicked.
i am able to stote a variable in jquery and check whether form is submitted or not and if submitted to load back the previously dynamically added dropdowns (html select box) but even though i load them back still i have a problem of getting the previously selected values of those dynamic dropdowns.
I have created a fiddler. http://jsfiddle.net/jBJSw/8/
My form
<form>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type="text" id="textbox1">
</div>
</div>
<input type="button" value="Add Button" id="addButton">
<input type="submit" value="submit Button" id="subButton">
</form>
Script
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
'<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
Appreciate if any help on finding a way to get the previously selected values after form submission. (this is needed because when a form is submitted with errors, these selected values should be same but now it refreshes and comes to default. also in a view scenario also this should be preloaded)
You will have to send back the selected value to the page from server side in the querystring or post header. then select the option accordingly in jquery on the base of the the value sent back.
Sorry for getting late have trouble in my work. Here's a possible solution for your problem.
DOM:
<form id="myform" method="post"> <!--adding id attribute-->
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type="text" id="textbox1">
</div>
<!--check if POST is established-->
<?php if($_POST): ?>
<?php if(count($_POST['mySelect']) < 0 ): ?>
<?php
//Recreate your select DOM
$arr = $_POST['mySelect'];
foreach($arr as $ind => $val){
echo '<select>';
echo '<option val="val" ' . ($val == "val" ? "selected" : "") . '>desc2</option>';
echo '<option val="val2" ' . ($val == "val2" ? "selected" : "") . '>desc</option>';
echo '<option val="val3" ' . ($val == "val3" ? "selected" : "") . '>desc3</option>';
echo '</select>';
}
?>
<?php endif; ?>
<?php endif; ?>
</div>
<input type="button" value="Add Button" id="addButton">
<input type="submit" value="submit Button" id="subButton">
</form>
SCRIPT:
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
'<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
//adding hidden inputs
$('#myFORM').on('submit', function(){
$('#myFORM select').each(function(){
slct = $('<input type="hidden" name="mySelect[]" value="' + $(this).val() +'">');
$('#myFORM').append(slct);
});
});
});