I have a dropdown I would like to load with options dynamically. I would also like to allow the user to "add" their own option and have it save to that dynamic list. So when anyone returns to that form, the new option is in the list. This is what I have so far - what do I need? Any information is greatly appreciated!
Here is my working project:
http://www.leskofolio.com/calendar/cal/gcal-script/index
The jsfiddle I was given with the ajax suggestion is here:
https://jsfiddle.net/o0qc8wvc/5/
Here is my dropdown - it doesn't pull from a dynamic "writable" list yet or, maybe it can?
<input type="hidden" name="action" value="<?php if($edit) echo 'edit';else echo 'insert';?>">
<input type="hidden" name="event_id" value="<?php if($edit) echo $event_data['id'];else echo '0';?>">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="form-group" >
<label for="event_title">Surgeon Name <span class="required">*</span> </label>
<select name="event_title" id="event_title" class="form-control required">
<option value="">Select a Surgeon</option>
<option value="BERASI"> BERASI</option>
<option value="BERGHOFF"> BERGHOFF</option>
<option value="BIGGS"> BIGGS</option>
<option value="BORUS"> BORUS</option>
<option value="BURKE"> BURKE</option>
<option value="CANNONE"> CANNONE</option>
</select>
</div>
<label for="event_title">Add a Surgeon</label>
<input type="text" class="addingElement">
<button class="addingButton" >Add</button>
</div>
I was told I could use Ajax to do this but he coudldn't help me with "additional PHP" that would be needed. Here is his ajax code:
$(document).ready(function(){
$('.addingButton').on('click', function(){
var newElement = $('.addingElement').val();
console.log(newElement);
var newOption = $('<option>').attr('value', newElement).text(newElement);
$('#event_title').append(newOption);
$.ajax({
url: 'link/to/my/index.php',
method: 'POST',
data: {
'newElement': newElement
}, success: function(data) {
// the new element was successfully added to the database
console.log('success ! ');
},
error: function(error) {
//there was an error while adding the new element.
console.error('there was an error : ' + error);
}
})
})
});
Again my selectbox works but I can't save the users addition. What am I missing or doing wrong? Again, any information is greatly appreciated!
You need to store the items they've added. The simplest way to do this will be to use localStorage. I've modified your code to store the element they add to a localStorage item called options, then on page load, I'm reading in that localStorage item and populating the list.
Since SO won't allow localStorage to be read in the sandbox code environment, here's a fiddle - https://jsfiddle.net/o0qc8wvc/7/
The new option you want to append should look like this
Var newoption ="<option value='"+ newElement +"'>" + newElement + "</option>"
I would recommend if you want to store it in a database after the new record has been inserted to reload the entire list -- remove the old options and load in the entire list --
Related
Next is html for text, button ,select elements:
<input type="button" id="addNextProjectID" value=" Add next project"/>
<input id="setNewProjectID" type="text" value=" project name "/>
<br>
<select id="selectProjectID" onfocus="onFocusSelectProject()">
<option value="Cats">Cats</option>
<option value="Dogs">Dogs</option>
</select>
</br>
Code which does add options to select element from text element on button click
function addNextProjectF(){
var x = document.getElementById("selectProjectID");
var option = document.createElement("option");
option.text = document.getElementById("setNewProjectID").value;
option.id = document.getElementById("setNewProjectID").value;
x.appendChild(option);
}
How to stringify all options from select and paste them to Json variable and then how to parse them back to select element.
My Select element has first 2 options set from html. I need to keep them.
Here i was thinking that the way would be to loop through the select element options and "append" each option to Json and reversal then to refill select element. But i did not meet any case of code to do this yet. Can you pleas help me with this code?
The case is also that i am not sure also how to use success function from ajax to fill the options of select. Anyway, maybe am thinking totally wrong approach to get to result i need.So how to proceed?
With next (code below) try i get
{"0":{},"1":{},"2":{}}
empty fields in DB. I presume "JSON.stringify(saveToprojectsList)" is wrong.
function saveToProjectsListF(){
whichProjectToSave=document.getElementById("selectProjectID").value;
saveToprojectsList=document.getElementById("selectProjectID");
var jsonProjectsListToPHP= JSON.stringify(saveToprojectsList);
console.log(jsonProjectsListToPHP);
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage/PsaveJson.php',
data: {
"sendProjectsList":1,
"whichProjectToSave":whichProjectToSave,
"jsonProjectsListToPHP":jsonProjectsListToPHP
},
success: function(data){
}
});
}
The question is rather broad, so I will only focus on the part where you have tried to address it with code, i.e. stringifying the options in the select list.
That code does not work as intended because saveToprojectsList is a DOM object, and will just yield an empty object when you try to stringify it to JSON. You can use map to extract the text contents of the option tags.
NB: As you use jQuery for $.ajax, you could use it in other places as well:
function onFocusSelectProject() {}
$('#addNextProjectID').click(function addNextProjectF(){
var value = $("#setNewProjectID").val();
$("#selectProjectID").append($("<option>").text(value).attr("id", value));
});
$('#save').click(function saveToProjectsListF(){
var whichProjectToSave = $("#selectProjectID").val();
var saveToprojectsList = $.map($("#selectProjectID>option"), function (op) {
return $(op).text();
});
var jsonProjectsListToPHP = JSON.stringify(saveToprojectsList);
console.log(jsonProjectsListToPHP);
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage/PsaveJson.php',
data: {
sendProjectsList: 1,
whichProjectToSave: whichProjectToSave,
jsonProjectsListToPHP: jsonProjectsListToPHP
},
success: function(data){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="addNextProjectID" value=" Add next project"/>
<input id="setNewProjectID" type="text" value=" project name "/>
<br>
<select id="selectProjectID" onfocus="onFocusSelectProject()">
<option value="Cats">Cats</option>
<option value="Dogs">Dogs</option>
</select>
<input type="button" id="save" value="Save"/>
</br>
I have integrated into a third party delivery service which I populate via Jquery.
[town] -> dropdown
[suburb] -> dropdown
On page load all the select elements are blank. When the user selects town, it then populates suburb.
Now in the event of a post to the server and a returned error, I want to set the form to the state the form was posted in by adding a select element to the correct drop down values.
As an example, user selects town_id 5 and suburb_id 105, form is posted, and returned due to an error. At this point I wish to populate town with value 5 and suburb with value 105...
HTML code:
<div class="form-group col-md-6">
Your town<span class="require">*</span>
<select name="town_id" id="mds_towns">
<option value="">Select your town</option>
<option value="2">Town1</option>
<option value="3">Town2</option>
<option value="4">Town3</option>
</select>...
<div class="form-group col-md-6">
Your town<span class="require">*</span>
<select name="suburb_id" id="mds_towns">
<option value="">Select your suburb</option>
<option value="2">Suburb1</option>
<option value="3">Suburb2</option>
<option value="4">Suburb3</option>
</select>...
I am no jquery expert and I am struggling with the concept of how to get the correct values on a return post.
One of my ideas was to have a special span element with each form field, so something like:
<span id="suburb_value" value="105"> <-----------------*** ADD THIS ***
<div class="form-group col-md-6">
Your town<span class="require">*</span>
<select name="suburb_id" id="mds_towns">
<option value="">Select your suburb</option>
<option value="2">Suburb1</option>
<option value="3">Suburb2</option>
<option value="4">Suburb3</option>
</select>...
Now when the page loads, I populate the span field via php
<span id="suburb_value" value="<?=$suburb_id;?>">
Next the javascript does an ajax call to the api and returns with the list of towns. I then check the value in the span fields and if a value is found, I add a select element to the associated select value...
Would this be on the right path?
Try this:
<script>
$(document).ready(function() {
var townId = <?= (isset($_POST['town_id'])) ? (int) $_POST['town_id'] : 0; ?>,
suburbId = <?= (isset($_POST['suburb_id'])) ? (int) $_POST['suburb_id'] : 0; ?>;
if (townId > 0 || suburbId > 0) {
// make your api call here with townId and suburbId
}
});
</script>
If I understand you correctly, you simply want to retain the selected values in the dropdowns after the page is reloaded on submit. In this case, using jQuery you could try something like:
<script>
$(function(){
var town_id, suburb_id = false;
// Here we assign values to these JS variables if they come through via PHP's $_REQUEST.
<?php echo (!empty($_REQUEST['town_id']) ? 'town_id = '.intval($_REQUEST['town_id']).';' : '') ?>
<?php echo (!empty($_REQUEST['suburb_id']) ? 'suburb_id = '.intval($_REQUEST['suburb_id']).';' : '') ?>
// Here we make the correspondings dropdown options selected, if needed.
if (town_id !== false) {
$('select[name=town_id] option[value='+ town_id +']').attr('selected', 1);
}
if (suburb_id !== false) {
$('select[name=suburb_id] option[value='+ suburb_id +']').attr('selected', 1);
}
});
</script>
More elegant way of doing this would be to pre-select the OPTIONs while outputting the page via PHP, but it's hard to suggest anything in this regard not knowing the structure of your application.
Good morning everyone.
I know this may have been asked before, but I'm finding it difficult to get a solution specific to my circumstances so I thought I'd ask here.
I am working on a site which has an account section for customers to add Pets to their inventory. The form itself has a "species" drop down which in turn triggers a change event on the "breeds" drop down in order to populate it with breed specific to the chosen species.
However, in the event of the user submitting the form prematurely without having selected a breed, an error will show but the breeds drop down is now un-populated as the trigger is on the change of the species drop down. So, to fix this I added a clause in the javascript to detect whether the species drop down has a value on load which in turn will trigger the function that populates the breed box. However, I get the error above when the page is reloaded and the box is not populated.
Here is the jQuery:
jQuery('#species').change(function () {
var species_id = $(this).val();
loadBreeds(species_id);
});
if (jQuery('#species').val() != "") {
var species_id = $(this).val();
loadBreeds(species_id);
}
function loadBreeds(species_id) {
console.log('loadBreeds is running');
jQuery.ajax({
url: "http://dev.mediaorb.co.uk/hiltonherbs.com/index.php?route=account/breeds",
type: "post",
data: "species_id=" + species_id + "&action=populateBreeds",
success: function (data) {
console.log('\nSuccess.');
jQuery('#breed option').remove();
jQuery('#breed').append('<option value="">-- Please select --</option>');
if (!data) {
jQuery('#breed').append('<option value="" disabled="disabled">No breeds found for selected species.</option>');
} else {
jQuery('#breed').append(data);
}
}
});
}
And here is part of the form HTML:
<div class="form-group">
<label for="species" class="required">Species</label>
<select class="form-control" id="species" name="species">
<option value="" selected="selected">-- Please select --</option>
<option value="1">Dog</option>
<option value="2" selected="selected">Cat</option>
<option value="3">Bird</option>
<option value="4">Horse</option>
</select>
</div>
<div class="form-group">
<label for="breed" class="required">Breed</label>
<select name="breed" id="breed" class="form-control">
<option selected="selected" value="">-- Please choose a species first --</option>
</div>
I have created a jsfiddle here to illustrate this functionality: http://jsfiddle.net/1961bgay/
Ideally you will need the console open (or firebug on Firefox) to see when the error occurs.
I think it may be relating potentially to the fact I have duplicated the jQuery selectors, but this is required in order to check and to add the trigger...any help appreciated, thank you!
Michael
You just have a small JS context/scoping error:
Change line 9:
From this:
var species_id = $(this).val();
To this:
var species_id = jQuery('#species').val()
Here is your working jsFiddle: http://jsfiddle.net/xgkefvbq/
Hope that helps!
I have a populated MySql database, my database has two columns (item_ID, item_title), and my HTML page has a select box, where all the item_IDs are stored, and below it I have a input box, now I want to do the following:
When the user selects an item_ID from the select box, it should go to the database and find out what is the item_title that belongs to that item_ID.
I am currently using PHP, I don't know how to carry such task.
Thank you in advance.
NB: I am okay populating the select box with all the available item_IDs. The only thing I am not sure how to implement is to retrieve the item_title dynamically as the item_ID changes, and display inside input box.
<select name='item_ID'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<input name='item_title' value='Should change as the item_ID changes' />
Let's say you generate your select element dinamically with PHP:
<?php
while($row = mysql_fetch_assoc($some_query)) {
echo "<option>" + $row["id"] + "</option>";
}
?>
Right? But now why not add the title in the same query and generate the select with it?
echo "<option data-title='" + $row["title"] + "'>" + $row["id"] + "</option>";
Nice, so your select will looks like:
<select name='item_ID'>
<option data-title="Title 1">1</option>
<option data-title="Title 2">2</option>
<option data-title="Title 3">3</option>
<option data-title="Title 4">4</option>
</select>
Now you bind a change event to the select like this:
$("#item_ID").on("change", function(e) {
var selectedOption = $("option:selected", this);
$("#item_title").val($(selectedOption).data("title"));
});
Don't forget to add id="item_title" to your title field.
So, with this approach you won't need an extra request and extra query to database in order to get the title by adding it in the same query that you use to create the select(with inner/left join if its from another table, I think). Thus, it will increase your application performance.
UPDATE:
The event binding should stay on the ready event of the document, like this:
$(document).ready(function() {
$("#item_ID").on("change", function(e) {
var selectedOption = $("option:selected", this);
$("#item_title").val($(selectedOption).data("title"));
});
});
And for more columns you just add them with data- prefix to the option element attributes:
<option data-title="" data-other-property=""></option>
And so on... Then to access it you use the same method:
$(selectedOption).data("title");
$(selectedOption).data("other-property");
Considering selectedOption stands for the option element.
Some references the worth a reading:
Using data attributes # MDN
$(document).ready() # jQuery Learning Center
I have an html form and ajax call that store data in MySQL via a PHP page.
The code for all three is copied below. (Please note the //)
All three work fine as long as I have the variables hard coded in the function where the ajax call stores them. However, when I comment out the hard coded variables and run it with the regular variables, it does not work.
JavaScript AJAX Call
$("#buttonSubmit").click(function() {
//var questionID = obj.Questions[i].questionID;
//var shortAnswerValue = document.getElementById('txtShortAnswerValue').value;
//var longAnswerText = document.getElementById('txtLongAnswerText').value;
var questionID = "SampleQID";
var shortAnswerValue = "Sample Short";
var longAnswerText = "Sample Long";
$.ajax({
type: "POST",
url: "SaveUpdatesTemplate.php",
data: "questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText,
}); // end ajax function
document.getElementById("txtLongAnswerText").reset();
}); // end button submit function
Associated HTML
Select Inspection or Project Phase
Select Inspection or Project Phase
<label for="selectSection">Select Inspection or Project Phase</label>
<select class="form-control" id="selectSection" name="selectSection">
<option> Select Inspection or Project Phase</option>
</select>
<button type="button" class="form-control" id="buttonStart" name="buttonStart" value="List Questions">Start - Click to Populate Question List</button>
<label for="selectQuestion">Select Task or Question to Update</label>
<select class="form-control" id="selectQuestion" name="selectQuestion" >
<option> Select Task or Question to Update </option>
</select>
<!-- short answer below -->
<label for="txtShortAnswerValue">Short Answer</label>
<select class="form-control" id="txtShortAnswerValue" name="txtShortAnswerValue">
<option value="1" selected>worst</option>
<option value="3">middle</option>
<option value="5">best</option>
</select>
<!-- long answer below -->
<label for="txtLongAnswerText">Long Answer / Notes</label>
<textarea class="form-control" name="txtLongAnswerText" id="txtLongAnswerText" rows=3>
</textarea>
Associated PHP Code
// Assign PHP variables to POST results from client
$questionID = htmlspecialchars(trim($_POST['questionID']));
$shortAnswerValue = htmlspecialchars(trim($_POST['shortAnswerValue']));
$longAnswerText = htmlspecialchars(trim($_POST['longAnswerText']));
//SQL STATEMENT
$sql="INSERT INTO Updates (questionID, shortAnswerValue, longAnswerText)
VALUES
('$questionID', '$shortAnswerValue', '$longAnswerText')";
You could do this:
data: encodeURI("questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText);
The problem is the spaces in var questionID, and so on. Also you have an unnecessary comma before the end of the Object you passed to $.ajax(), right after your data property value.