how to add new select box after clicking a button in jquery - javascript

i dont know if its possible using jquery,..i have a select option that has an array of data came from database and what i want is that whenever i click a button, another select option will popout like the first select option..
here is the code of my select option
<select class="form-control" name="room[]" id="room[]">
<option value="" default>Select</option>
<?php
$room = $subjectsClass->room();
foreach ($room as $key => $value) {
echo '<option value=" ' . $value['room_id'] .' ">' . $value['room_no'] . '</option>';
}
?>
</select>
<button type="button" class="btn btn-default" id="addRooms" >Add more Rooms?</button>
<script>
$('#addRooms').click(function(){
//append another select box with data from database,..how??
});
</script>

Let's say you have that wrapped into a div like:
<div id="the_div_of_wrapping"> all your stuff </div>
Then I would do:
var the_select = $("#room[]");
var the_id = the_select.prop("id");
var the_number_of_selects = $("select").length;
var the_div_of_wrapping = $("#the_div_of_wrapping");
the_select.clone().prop("id", the_id + the_number_of_selects);
the_div_of_wrapping.append(the_select);
.
Update:
As discussed in the comments, I would remove id since it is unnecessary and then the code would be:
var the_select = $("#room[]");
var the_div_of_wrapping = $("#the_div_of_wrapping");
the_select.clone();
the_div_of_wrapping.append(the_select);

Related

How to I save a list group in SQL database?

I have code in html that adds data in a list by selecting the data in the combo box and clicking on the add button. I am encountering an error "undefined index: subjectlist" when submitting the form. Appreciate your advise this? Thank you. I am still an newbie in web programming.
<h4>Subjects</h4>
<ul class="list-group list" id='subjectlist' name='subjectlist' >
</ul>
<div class="form-group">
<input class="submit" name="submit" type="submit" value="Save">
</div>
</form>
<button class="add_field_button" onclick="getsubject()">Add Subject</button>
<button class="add_field_button" onclick="removesubject()">Remove Subject</button>
<script>
function getsubject(){
var ul = document.getElementById("subjectlist");
var candidate = document.getElementById("st");
var SelectedValue = candidate.options[candidate.selectedIndex].text;
var li = document.createElement("li");
li.setAttribute('class',"list-group-item");
li.setAttribute('id',"subjectlistitem");
li.appendChild(document.createTextNode(SelectedValue));
ul.appendChild(li);
}
</script>
<?php
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$sectioncode = $_POST['sc'];
$sectiongroup = $_POST['ccg'];
$selectedsubject = $_POST['st'];
$subjectlist = $_POST['subjectlist'];
$i = 0;
foreach ($subjectlist as $qst) {
$sql = "INSERT INTO sectionsubject(sectioncode, subjectcoden) VALUES ('" . $csectioncode . "',
'" . $subjectlist[$i] . "')";
if ($link->query($sql) === TRUE) {
echo "success";
} else {echo "error" . $link->error;}
$i++;}
}
?>
because $_POST,$_GET only deal with <input> tags and <ul>,<li> are not input methods.

jquery multiple select list update failed

In my php project I have a multiple select dropdown and I'm using jquery.multiple.select.js.
My view part is
<div class="form-outer box">
<div class="span12 ">
<label>Partner</label>
<select class="span9 check_select " name="partner[]" id="partner" multiple="multiple" >
<!--<option value="-1">Select</option>-->
<?php foreach ($member as $memberpart) : ?>
<option value="<?php echo $memberpart->members_id; ?>">
<?php echo $memberpart->members_first_name; ?>
</option>
<?php endforeach; ?>
</select>
<a href="#paradd" class="btn" role="button" onclick="clear_message()" data-toggle="modal">
<i class="icon-plus pull-right" style="margin-top:5px;"></i>
</a>
</div>
</div>
Here I have a PLUS button (<a> tag) which opens a modal to add new partner. Now I want to update the multiple select dropdown when a new partner is added using the modal and I call a function when modal is closed as follows,
function bulid_select_box(select_box,path,doselect){
var base_url = $("meta[name=baseurl]").attr("content");
$.ajax({
url: base_url + path,
success: function(data) {
var json = jQuery.parseJSON(data);
$(select_box).find('option').remove();
$(select_box).append('<option value="-1">Select</option>');
var setselect = '';
if(doselect){
setselect = 'selected';
}
for(var i=0; i < json.length; i++){
if((json.length -1)== i){
$(select_box).append('<option ' + setselect + ' value="' + json[i].value + '">' + json[i].option + '</option>');
}else{
$(select_box).append('<option value="' + json[i].value + '">' + json[i].option + '</option>');
}
}
$(select_box).trigger("chosen:updated");
$(select_box).data('chosen').activate_action();
bulid_select_trigger(select_box);
}
});
}
When using this the new value does not get inserted in the list, but when I am inspecting the values shows in the <select> tag its style is display="none".
The actual list shows in a <div> with class=ms-drop with <li> tags.
I think the list is not updated when am using
$(select_box).trigger("chosen:updated");
What am to do to update the list?
If you are using this library the way to refresh the list is
$select.append($opt).multipleSelect("refresh");

Javascript for creating breadcrumbs with links to each breadcrumb?

I'm trying to create breadcrumbs with the user's selection from a listbox that updates the breadcrumbs' last value.
I've gotten it to work, but you can't click on 'Home' or 'Store' to go to previous pages. So I tried adding links to the values in my script, but it continues to print the link with the string rather than just make the string a link.
Any tips?
$("select")
.change(function () {
var val = "";
var str1 = "Home";
var str2 = "Store";
var str3 = str1.link("home.php") + " / " + str2.link("store.php") + " / " + val;
$("select option:selected").each(function () {
val = $(this).text();
});
$(".breadcrumbs").text(str3);
})
.change();
This is my HTML & PHP where it's pulling distinct items from my database and populating a list box:
<div class="breadcrumbs col-sm-4">
<!-- Update this based on the selected box using the script at the bottom of the page-->
<!-- bread crumbs -->
</div>
<div class="col-sm-offset-3 col-sm-2">
<select id="productselect" class="form-control" name="category">
<option value="All Products">All Products</option>
<!-- Populate the listbox with distinct category of items from the database -->
<? do { ?>
<option value='"$row[0]"'>
<?="$row[0]" ?>
</option>;
<? } while($row=m ysqli_fetch_array($result)) ?>
</select>
<? mysqli_free_result($result); mysqli_close($db); ?>
</select>
</div>
If your string contains HTML (which it does), you need to use jQuery's .html() method to add it, instead of .text() (which escapes HTML):
$(".breadcrumbs").html(str3);
Also, you probably want to place the block above it ($("select option:selected").each(...)) before you set str3.

Add form fields dynamically with php

Referring to this post. Add form fields dynamically populated dropdown list with php I have used his code but will modify it to fit my needs since I pretty much nothing about javascript. I have everything working except when you press the + button it never creates more input boxes. Any help would be great.
This my php file
<?php
session_start();
require_once("dbconfig.php");
?>
<html>
<head>
<script type="text/javascript" src="addfish.js"></script>
</head>
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
while($speciesq = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value=\"" . $speciesq['species'] ."\">" . $speciesq['species'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
</html>
My addfish.js file
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
;
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1')
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.speciesnumber1.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.speciesweight.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
This is my getlist.php
<?php
session_start();
include("dbconfig.php");
$stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
$result = array();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = array(
'value' => $rows['species'],
);
}
echo json_encode($result);
?>
Your code is using jQuery, but I don't see where you include this library. Try to put this code before include addfish.js in header :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you need to add rows with this fields dynamically I suggest you make a row which is the original row:
<div class="rows" data-rows="1">
<div class="row row-first">
<select name="row[0][select_name]">
<option value="1">Some value</option>
</select>
<input type="text" name="row[0][text_name]" />
</div>
</div>
and the javascript
<script type="text/javascript">
$('#add_row').on('click', function(){
var row = $('.row-first').clone(); // Clone the first row
var rows = parseInt($('.rows').attr('data-rows'));
rows++;
$('.rows').attr('data-rows', rows);
row.removeClass('row-first'); // Prevent multiple rows cloning
$(row).find('[name]').each(function(){
var name = $(this).attr('name');
name = name.replace(/\[[0-9+]\]/, '[' + rows + ']');
$(this).attr('name', name);
$(this).val("").change(); // Null the select
});
$('.rows').append(row);
});
</script>
So what you do is clone the first row and remove the class, which you search. Increment the rows count and replace all names in you row with the new row number e.g. row[0][name] becomes row[1][name], and append the row.
Also when you edit the rows you MUST put set the data-rows to the exact number. You can do it like count($myRows). And when you write the remove row function DO NOT REMOVE the first row.
Hope it hepls.
// You can use this
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);

Showing a specific graphic onchange

I currently have a piece of JavaScript that takes the value and the selected text from the PHP dynamic dropdown menu and passes it through to a input box for editing.
Questions:
How could I pass a PHP item through the JavaScript to show the specific image for the selected value when it is selected?
How could I make the selected text echo into the input box on select?
$('#captionSelect').change(function(){
$('#captionInput').val($("#captionSelect option:selected").html()).show();
});
<select name="captionSelect" id="captionSelect">
<?php foreach ($get_images as $image){
echo '<option value="'.$image['id'].'">'.$image['description'].'</option>';
};
?>
</select>
<select name="captionSelect" id="captionSelect">
<?php
foreach ($get_images as $image){
echo '<option title="'.$image['thumbname'].'" value="'.$image['id'].'" id="captionOption_'.$image['id'].'">'.$image['description'].'</option>';
};
?>
</select>
<input id="captionInput" type="text" />
<img id="preview" />
<script type="text/javascript">
$('#captionSelect').change(function(){
var id = $(this).val();
var caption = $('#captionOption_' + id).html();
var thumbname = $('#captionOption_' + id).attr('title');
$('#captionInput').val(caption);
$('#preview').attr('src', '/path/to/pictures/' + thumbname + '.jpg');
});
</script>

Categories