jquery multiple select list update failed - javascript

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");

Related

How to use multiselect() without removing existing values and add new values based on another selection

I'm with an e-learning project and working on the section of massive matriculation. I use a search box to look for students´ name, and add those values to a list. The problem appears when I try to look for other students' name and add those values to the existing list. This part reloads and all the previous values disappear. How can I display the result of new values and add them to the chosen list without removing the old one.
Code to display list (detail.php)
<p>
<label> <?php echo $string['LBL_PROGRAM_NAME']; ?>: </label>
<input type="text" id="program_name" name="program_name" class="tam1" maxlength="200" value="<?php echo $program_name; ?>" />
</p>
<br class="clear"/>
<center>
<input type="button" class="btn" name="buscar_programs" value="<?php echo $string['LBL_SEARCH_PROGRAMS']; ?>" onclick="javascript:loadPrograms();"/>
</center>
<p>
<label><b><?php echo $string['LBL_PROGRAMS_SELECT']; ?>: <span class="rojo">*</span></b></label>
<span id="area_programs">
<select id="programs" class="multiselect" multiple="multiple" name="programs[]">
</select>
</span>
</p>
Function loadPrograms() (detail.php):
function loadPrograms(){
$.ajax({
url: ruta_fichero_ajax+"loadProgramsItinerario.php?a1="+$('#program_name').val()+"&a2="+$('#center_id').val(),
dataType: 'json',
async: false,
success: function(datos){
var strHTML = '<select id="programs" name="programs[]" class="multiselect" multiple="multiple">';
if (datos.length>0){
$.each(datos, function(index, dato) {
strHTML += '<option value="' + dato.id + '">' + dato.name + '</option>';
});
}
strHTML += '</select>';
document.getElementById("area_programs").innerHTML = strHTML;
$("#programs").multiselect();
}
});
}
I'm a junior and still have many things to learn with Javascript. Thanks for your help.
To append new values to the options list, you can use below code(with jQuery cause you seem to be using jQuery)
$("#programs").append(new Option('TEXT', 'VALUE'));
Or using vanilla JS
selectElement = document.getElementById('programs');
selectElement.options[selectElement.options.length] = new Option('TEXT', 'VALUE');
Alternatively you can check this or w3schools for detailed explanation.

How to pass multiple workplace names with same names/ids from form via AJAX to another php page so I can update my MySQL table.

I found solutions for similar questions from stackoverflow as below, but they didn't work for me.
Possible Solution 1 here
Possible Solution 2 here
For just one workplace input field, this code works perfectly fine, but by using jQuery functions, I am prepending multiple workplace field dynamically.
Also, I don't have any trouble updating data in my MySQL database as far as I am using only one input field for workplace.
But when I prepend multiple input fields for workplace, I have trouble passing my different workplace name to php script.
So far, I have tried using solutions such as I used class="workplace" instead of id="workplace", but with that I don't even get values of my input field even on the same page when I used "alert(companyname);" to see if I get to see submitted values in alert. But no!
Also, I tried making my and other ways such as name="workplace['+index+'][name]", etc. None worked.
Database name: workplacedb
table name: companyname
fields: c_id ,user_id, workplace.
$(function() {
var count = 0;
/* WORKPLACE codes start here */
$('.add-workplace').click(function() {
var index = $('.workplace-input').length + 1;
//$('.add-workplace').hide();
$(".collapse").collapse('show');
$('.workplace-lines').prepend('' +
'<div class="input-group workplace-input">' +
'<input type="text" name="workplacename" id="workplace" class="form-control"/>' +
'<span class="input-group-btn">' +
'<button class="btn btn-danger btn-remove-workplace" type="button"><span class="glyphicon glyphicon-remove"></span></button>' +
'</span>' +
'</div>'
);
});
$(document.body).on('click', '.btn-remove-workplace', function() {
$(this).closest('.workplace-input').remove();
});
$('.add-workplace').one('click', function() {
count = 1;
});
$('.add-workplace').click(function() {
if (count > 0) {
$('.workplace-lines').append('<span class="input-group-btn main-btn">' + '<button class="btn btn-success btn-workplacesubmit" type="submit" name="submitWeb"><span class="glyphicon glyphicon-check">Submit</span></button>' + '<button class="btn btn-danger btn-workplacecancel" type="button" name="cancel" style="margin-left:15px"><span class="glyphicon glyphicon-remove">Cancel</span></button>' + '</span>');
count = 0;
}
});
// Cancel button click for workplace fields
$(document).on('click', '.btn-workplacecancel', function() {
$('.workplace-input').remove();
$('.main-btn').remove();
count = 1;
});
var workplace_form = $('#workplaceinfo');
workplace_form.submit(function(event) {
var companyname = $('#workplace').val();
alert(companyname);
if ($.trim(companyname) != '') {
$.post('about.php', $("#workplaceinfo").serialize(), function(data) {
$('.workplace-lines').hide();
$('.main-btn').hide();
$('#results').html(data);
//alert(data);
});
}
// Prevent default form action
event.preventDefault();
});
});
<!-- about.php here --> <?php require_once("home_userinfo_retrieve.php");
$mysqli=new mysqli('localhost',
'root',
'',
'databasename');
$sql="UPDATE tablename SET workplace=? WHERE user_id='$userid_logged_in'";
$stmt=$ mysqli->prepare($sql);
$stmt->bind_param("s",
$_POST['workplacename']);
$stmt->execute();
$stmt=$mysqli->prepare("SELECT * FROM detailed_user_info WHERE user_id = ?");
$stmt->bind_param("s",
$userid_logged_in);
$stmt->execute();
$result=$stmt->get_result();
while($row=$result->fetch_object()) {
$rows[]=$row;
}
?> <ul> <?php foreach ($rows as $row):?> <li> <?php echo $row->workplace;
?></li> <?php endforeach;
?> </ul>
<form action="about.php" method="post" name="workplaceinfo" id="workplaceinfo">
<div class="form-group workplace">
<div class="workplace-lines">
<h5 class="add-workplace"> <a><span class="glyphicon glyphicon-plus"></span> Add your workplace </a> </h5>
</div>
<h5 id="results">
</h5>
</div>
</form>

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

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);

i want submit form on last select onchange i have multilple selects, options are generated dynamically

Submit form on last select onchange: I have multiple selects, options are generated dynamically.
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
im using select onchange at the same time adding select also this code submit only first level select. I have many levels inside them and options are generated dynamically. I want to submit on last select onchange.
<form id="search_mini_form" action="<?php echo $catalogSearchHelper->getResultUrl() ?>" method="get">
<select id="first_cat" onchange="showCat(this, 2);this.form.submit()" name="<?php echo $catalogSearchHelper->getQueryParamName() ?>" value="<?php echo $catalogSearchHelper->getEscapedQueryText(); ?>" class="input-text" >
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<button type="submit" title="<?php echo $this->__('Search') ?>" class="button"><span><span><?php echo $this->__('Search') ?></span></span></button>
</form>
var select = document.getElementsByTagName('select')[0];
function myFunction(e){
if(e.value == select.options[select.options.length-1].text){
alert("Last value selcted")
}
}
var select = document.getElementsByTagName('select')[0];
function myFunction(e){
if(e.value == select.options[select.options.length-1].text){
alert("Last value selcted")
}
}
<select onchange="myFunction(this)">
<option>item1</option>
<option>item2</option>
<option>item3</option>
<option>item4</option>
<option>item5</option>
</select>

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