Showing a specific graphic onchange - javascript

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>

Related

Using DIV like dependent dropdown lists [PHP + JS]

I have a DIV element as drop-down in PHP as below:
<div id="files" value="fileselect" selected="selected">Choose Folder1
<input type="hidden" name="test" id="hiddenfield" />
</div>
<div id="files2" value="fileselect2" selected="selected">Choose Folder2
<input type="hidden" name="test2" id="hiddenfield2" />
</div>
Now I try to get the value of selected option as follows:
<?php $content = ?>
<script type = text/javscript>
document.getElementById("files").value;
</script>
<?php echo $content; ?>
but I get unknown variable $content error.
And, I tried to create 'change' event handling in DIV element as follows:
$(document).ready(function()
{
//Bind a change event to the folder selector
$("#files").change(function()
{
var dir = $(this).val();
// Get file names in directory dir and pass it to the next drop-down DIV
$.get("listfiles.php", {"dir":dir}, function(response){
//Show the files
$("#files2").html(response);
//alert($('#files2 option:selected').val());
alert(response);
$(response).appendTo('#hiddenfield2');
});
});
});
But this doesn't help passing the 'response' to the second DIV "files2".
I need to use the two DIVs like dependent drop-down lists. I make the dropdown-list "selection1" interact with DIV "selection2" like dependent dropdowns as follows:
<select name="field1" id="selection1">
<option selected="selected" name ="selection1">Folder 1</option>
<?php
$selections = array('Folder A', 'Folder B', 'Folder C');
foreach($selection as $selections){
?>
<option value="<?php echo strtolower($selection); ?>"><?php echo
$selection; ?></option>
<?php
}
?>
</select>
$("#selection1").change(function()
{
var dir = $(this).val();
$.get("listdirs1.php", {"dir":dir}, function(response){
//Show the files
$("#files").html(response);
// alert($('#selection2 option:selected').val());
//alert(response);
$(response).appendTo('#selection2');
});
});
But this doesn't work in case both "selection1" and "selection2" are DIVs.
I already referred to how to submit a div value in a form stackoverflow answer
I am all new to PHP and JavaScript. Please help. Thanks in advance.

Multiple actions on a Single Change Event with JQuery/Javascript

I need to implement this js in order to fill in different fields on change event of a select field.
<select class="form-control" name='brands_list'>
<option value="0">Seleziona il produttore</option>
<?php
while ($listabrand=mysqli_fetch_array($brands)){
echo '<option value="'.$listabrand[0].','.$listabrand[1].','.$listabrand[2].'">'.$listabrand['0'].' - '.$listabrand['1'].'</option>';
}?>
</select>
This is the js to implement. I should add a second action that fill in the input field named 'brand_link' assuming the array value [2]:
<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
</script>
I made several attempts but without results such as
<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
$('select[name="brands_list"]').change(function(){
$('input[name="brand_link"]').val($('select[name="brands_list"] option:selected').text()[2]);
});
Any help?
You can do it all within the one function. The reason your pastebin didn't work is because 1) you aren't operating on the .val() of the selected item (rather the element itself) and 2) you didn't split the value by comma, like you split the .text() by hyphen.
$('select[name="brands_list"]').change(function(){
var $selectedOption = $('select[name="brands_list"] option:selected');
$('input[name="brand_name"]').val($selectedOption.text().split(' - ')[1]);
$('input[name="brand_link"]').val($selectedOption.val().split(',')[2]);
});
$(".form-control").change(function()
{
//alert( this.value );
var sl_value = this.value;
$('input[name="brand_name"]').val(sl_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="brand_name" value="">
<?php $listabrand=mysqli_fetch_array($brands);?>
<select class="form-control" name='brands_list'>
<option value="Seleziona il produttore">Seleziona il produttore</option>
<?php
foreach($listabrand as $brand){ ?>
<option value="<?php echo $brand;?>"><?php echo $brand;?></option>
<?php } ?>
</select>
in first step, get dropdown selected value in jquery on change. And save this value in jQuery variable. And then insert this value in textbox using jQuery. Thanks

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

changing the Placeholder attribute in html input field

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

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

Categories