option onChange on currentpage using database information - javascript

I've written a query that takes the usernames from the database and puts them in s like this:
<?php
$username_set = get_all_usernames();
while ($username = mysql_fetch_array($username_set)){
echo "<option>" . $username['username'] . "" . "</option>";
}
?>
That works fine but now I want to add a onchange function to my tags. I've done it like this:
<select name="user_result" onChange="top.location.href = this.form.user_result.options[this.form.user_result.selectedIndex].value,'_self';">
That works fine too, it is redirecting to the selected option. But I want to select a option and stay at the same page and display the (coming) information that username contains. But for now printing the username below the would be good enough.

If you want to execute code on change of a select, it's easy to include this in a javascript function. Not sure if you want the javascript or the jquery solution, so I'll include them both.
Plain javascript:
function show_user(data) {
var el = document.getElementById("show_username").innerHTML = data;
}
jQuery solution:
function show_user(data) {
$("#show_username").html(data);
}
Then you call this function on the select change:
<select name="user_result" onchange="show_user(this.options[this.selectedIndex].value);">
<option>--select a user--</option>
<option>username</option>
<option>username 2</option>
</select>
<div id="show_username">this will update to the selected user name</div>
jsfiddle for plain javascript: http://jsfiddle.net/CwFs5/
jsfiddle for jquery: http://jsfiddle.net/5PuX3/

Related

Submit a value from dropdown without refresh then use the value re calculate a price

I have a select option to add accessories to a product. What I want to do is recalculate the price without have to refresh the page. This is what I'v got so far:
<form action="" method="post">
<select name="option" onchange="this.form.submit()">
<option value="15">Acc1</option>
<option value"30">Acc2</option>
<option value"45">Acc3</option>
</select>
</form>
$oldprice ='678';
$option = $_POST['option'];
$newPrice= $oldprice + $option;
This works great, however it has to refresh the page. Is there a way to recalculate the new price without having to refresh the page.
And also use the option value in other places on the page for example
If ($_POST['option] == '15'){ \do something}
Any help welcome
You could use ajax or if the needed information is already in the page which it seems to be based on your example code, then you could change the onchange to be a function:
onchange='updatePrice()'
Sample function code:
function updatePrice(){
var e = document.getElementsByName("option")[0];
var accessory_value = e.options[e.selectedIndex].value;
//additional code to update the price where
}
Hook onchange event in select tag.
Ex:
<select onChange="calculate(e)">
// option here
</select>
*.js:
function calculate(e) {
console.log(e.target.value);
}

Using Jquery to change form based on user input

I have a form with a select tag. I need my form to change based on the selection from the user. I am given to believe that the easiest way to do this is to use JQuery.
Here is my code:
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
</div>
<div id="addhtml"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
alert("event triggered");
var val = $(this).val();
if (val == "number" || val == "symbol") {
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
} else if (val == "letter") {
$("#addhtml").html(<?php include("html/form_letter.html"); ?>);
} else {
$("#addhtml").html(<?php include("html/form_other.html"); ?>);
}
});
});
</script>
Note: the php while statement just sets up the current three options of "number", "symbol" or "letter" with ids of 1,2 and 3 respectively
When I change the category, it does not trigger the jquery.change()
I would like to code the form without using the addhtml div but am willing to use it if necessary.
Questions:
Is the reason the change function is not being triggered because I am using php to set the values of the select options?
If so how can I resolve?
If not, why isn't it being triggered?
How can I accomplish my goal of not using the addhtml div?
Is there a better way to accomplish what I am going for?
Thanks in advance.
EDIT:
Answers to initial questions: As stated by bistoco, php is pre compiled by the server and sent in as html so the issue is not from using php to set the values of the select tag.
I have now determined that it is due to the content of my php include files. I have determined that it registers the change event and loads the content just fine if my file is simple like this:
"<div><label>New Number</label></div>"
but if I add any white space or \n characters for human readability like this:
"<div>
<label>New Number</label>
</div>"
Not only does it not work, but it also completely skips the change event.
New Questions: Does the jquery html function have a list of illegal characters that would cause it to fail? Why is it not even registering the change function when it doesn't like the contents of my php include file?
First thing that you must understand is that php runs on the server, all the output is rendered and sent as html code to the browser, and is not available there.
That said, you have at least 2 options :
1.- echo all form options, each one inside a div, that you can hide/show based on the selected choice.
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
<!-- ECHOING ALL FORM OPTIONS -->
<div class="option-form" id="form-option-symbol"><?php include("html/form_number.html"); ?></div>
<div class="option-form" id="form-option-letter"><?php include("html/form_letter.html"); ?></div>
<div class="option-form" id="form-option-other"><?php include("html/form_other.html"); ?></div>
</div>
<style>
div.option-form {
display:none; /* HIDE ALL DIVS BY DEFAULT */
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
// HIDE ALL DIVS
$('div.option-form').hide();
var val = $(this).val();
if (val == "number" || val == "symbol") {
$('form-option-symbol').show();
} else if (val == "letter") {
$('form-option-letter').show();
} else {
$('form-option-other').show();
}
});
});
</script>
2.- Using a template system or load partial html pieces with ajax.
PHP Is a pre-processor so adding later into the website is useless. Just create your form with either setting its html or by using .prepend() or .append() with your form elements.
<form class="myform">
</form>
and in jquery
$('.myform').html('<input type="submit">');
or
$('.myform').append('<input type="submit"');
EDIT :
Read your code wrong looked up
<?php include('test.html'); ?>
don't think that would work.
Instead of
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
and such, try
$("#addhtml").html("<?php include("html/form_number.html"); ?>");
so that the html will be treated as a string.
Also make sure the form files don't have tags such as html, head, and body, and only contain the actual form.
EDIT: I just saw that #nnnnnn already stated this, gotta give credit where credit is due
I think you might just need to change your variable "val" declaration to get your code to work.
I don't think
var val = $(this).val();
will work. Based on the comparison you are making, I believe it should be:
var val = $(this).children("option:selected").text();
which will allow you to get the text value of the select element's selected option.

Add new item in a select tag and refresh it without refreshing the whole page using jquery

How can I refresh a select tag after adding new item into it using Jquery.
HTML :
<select id="exam_select" class="exam_select" name="exam_select" value="Select Exam">
<option value="">Select Exam</option>
<?php
while($row=mysql_fetch_assoc($exam)):
?>
<option value="<?php echo $row['e_code'];?>"><?php echo $row['e_code'];?></option>
<?php
endwhile;
?>
</select>
<input type="text" id="add_new_deg_field" class="hide_show" placeholder="New Exam Name"/>
<button id="add_edu_deg" class="hide_show">Add</button> <p id="save_exam" class="hide_show p_hide_show"></p>
JQuery :
$.ajax({
type:'post',
url:'exam_entry.php',
data: 'add_new_deg_field='+ $('#add_new_deg_field').val(),
success: function(reply_data){
$('#save_exam').html(reply_data);
}
});
return false;
}
By this code I can save new item in my database table by clicking 'add_edu_deg' button. But can't refresh the select tag options. How can I do it using jquery. I search a lot but can't find any solution. Plz help. Thank you.
I am assuming that you want to remove the selected <option> once it has been selected since you haven't defined what you mean by refresh
If that is the case , within the success callback you can do:
$('#exam_select option:selected').remove();
If this is not your intent, the question is not clear enough
You can add an option to a select input with append.
<select><option>Option 1</option></select>
<button>Add option</button>
var x = 2;
$("button").click(function(){
$("select").append("<option>Option "+x+"</option>");
x++;
});
If you somehow save your option to x with ajax (I don't know how, never used ajax before), then execute append on your select, it will be added to the list without needing to be refreshed.
Here is a fiddle of it.
http://jsfiddle.net/8ka5Y/
$('#addOption').on('click',addOption);
var i = 0;
function addOption(){
$('#mooSelect')
.append($("<option></option>")
.attr("value",i++)
.text("Option " + i));
}
which is pretty much what is in the question
What is the best way to add options to a select from an array with jQuery?

How to show dropdown selected data in textbox

I want to show the drop down selected value in textbox.
This is my design.
This is my php code for drop downlist...
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("storedb", $con);
$s=mysql_query("select * from dealerdetail order by Dealer asc ");
?>
Select Dealer Name:
<select name="dealer" id="dealer">
<option value="">---- select Dealer -----</option>
<?php
while($dd=mysql_fetch_array($s))
{
?>
<option value="<?php echo $dd['D_id'] ?>"><?php echo $dd['Dealer'] ?></option>
<?php
}
?>
</select>
Please help.
I think you are looking for
$('#dealer').val(); //return selected value
$( "#dealer option:selected" ).text() // return selected options text
Use the change event and text property of select box to access the value
$('#dealer').change(function () {
$("#idOfTextBox").val($("#dealer option:selected").text());
});
use jquery:
Live demo : http://jsfiddle.net/t6YHK/25/
$('#dealer').change(function () {
$("#your_input_id").val($(this).val());
});
Use this:
$("#dealer").change(function(){
$("textarea").val( $(this).val() );
});
AngularJS
http://angularjs.org/
Scroll down to below the black area.
Seems like you're taking your first steps in web development, and for this, i strictly recommend that you stop using DreamWeaver to learn more about the code and how things go.
Each element in your web page is in the DOM (see HTML Document Object Model). So using native javascript all of your elements using :
document.getElementById("elementId")
And this is ALL what you need. All other solutions using frameworks will use this line of code whether you see this or not.
so for your specific question we will create a javascript function to be used in the event of value change of your dropdown list (assuming your text field's id is myText)
function updateMyText()
{
var dd = document.getElementById("myDropDown");
var ddtext = dd.options[dd.selectedIndex].text;
document.getElementById("myText").value = ddtext;
}
to call it when a dropdown list item is selected you need the attribute onchange
<select name="dealer" id="dealer" onchange='updateMyText()'>

how to Target an option from pull down with js to apply more code

a friend asked me to help him with a form, a client of his wants to make a form a bit more dynamic...my javascript is minimal at best since i just started learning.
He asked me something along the lines of " how can i make a form show another pull down ONLY WHEN a certain option is selected "
in the example he gave me, by default when page loads,he has a pull down menu which has 2 options, MANHATTAN and option two is BROOKLYN.
If Manhattan is chose, that reveals another pull down with zips for manhattan, if Brooklyn is chosen the same for BK.
in sample html, something along the lines like this:
<div>
<form>
<select name="boro" id="boro">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
i want to target/capture the option chosen by the user above on the pull down menu, to then activate this function(below).
according to his request what i guess id do is,(as a newbie), then as far as the .js goes (pseudo code):
<script type="text/javascript">
function valBoro (){
if( brook is chosen){ document.getElementById('empty2fill').innerHTML=" new dropdown code here")
}
}
</script>
aside from not knowing, my main problem is i dont know how to target the option chosen in the menu to thereafter, apply the function (which will be written later)
any ideas, tips etc are greately appreciated.
thanks in advance
Another option is to create the two dropdown lists and set the style display to "none". Then you can catch the onChange event and set display to "" based on the value of the select element.
function showZip() {
var boro = document.getElementById("boro");
if (boro.value == "manhattan") {
var zipManhattan = document.getElementById("zipManhattan");
zipManhattan.style.display = "";
}
}
And in the html
<div>
<select name="boro" id="boro" onchange="javascript:showZip();">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<br/>
<select name="zipManhattan" id="zipManhattan" style="display:none;">
<option value="zip1" id="zip1">1111</option>
<option value="zip2" id="zip2">2222</option>
</select>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Here is a link to a jsfiddle showing example code.
http://jsfiddle.net/WKqth/
Example markup:
<div>
<form>
<select name="boro" id="boro">
<option value="" id="none">Select a boro.</option>
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Example js
// include this js below the form in the body, or wrap it in a function and assign that to window.onload, or use a library that provides onDomReady (in jQuery, $(document).ready(function () ... });
var selectElement = document.getElementById('boro');
var showBoroSelect = function () {
// find the selected element
var selectedOption = selectElement.options[selectElement.selectedIndex].id,
// find the element that will contain the new drop down
containerElement = document.getElementById('empty2fill'),
// define the html for the manhattan drop down
manhSelectInnerHTML = '<select name="secondary"><option value="derp">manh derp?</option><option value="herp!">manh herp!</option></select>',
// define the html for the brooklyn drown down
brookSelectInnerHTML = '<select name="secondary"><option value="derp">brook derp?</option><option value="herp!">brook herp!</option></select>',
newInnerHTML;
// determine which html to use based on the selection
if (selectedOption === 'manh') {
newInnerHTML = manhSelectInnerHTML;
} else if (selectedOption === 'brook') {
newInnerHTML = brookSelectInnerHTML;
} else {
// no boro was selected, hide the menu
newInnerHTML = '';
}
// set the container to the new innerHTML
containerElement.innerHTML = newInnerHTML;
};
// when the boro select changes, show the new menu
selectElement.onchange = function () {
showBoroSelect();
};
// if you select a boro and reload the page, the boro may already be selected (for example, firefox might do this)
// this will set the boro menu initially before the user changes it
showBoroSelect();
You want to handle the change event of your "boro" select element.
I've put a plain-JS example solution on jsfiddle at http://jsfiddle.net/FHArd/1/
This creates three select lists - one is your "boro" and the other two are the zip code lists, but they are hidden via CSS until a selection is made.
The change event handler simply adds and/or removes classes from the zip code select elements; the CSS hides or shows the lists based on the class "active" that is attached to the zip code select list.
Note - being there in jsfiddle the way you start things up is a little different than normal. You'd really run your setup function at the onload or ondomready event.
This should do it.
<select name="boro" id="boro" onchange="valBoro(this)">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<script type="text/javascript">
function valBoro(dropDown) {
if (dropDown.options.[dropDown.selectedIndex].value.equals("manhattan")) document.getElementById('empty2fill').innerHTML = "newHTMLCode";
//change "manhattan" to whatever option you want to use
}
</script>

Categories