Save and retrieve options of select element to and from Json - javascript

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>

Related

How to pass a javascript return value to spring path variable

My goal is grab the return value of a javascript function an then pass as spring path variable
I tried to do this code:
The dropdown, populate data that the user want to pick up
<label for="cust">Select a customer</label> <select
id="cust" class="form-control">
<option th:each="customer: ${customers}"
th:value="${customer.id}" th:utext="${customer.name}" />
</select>
The script, It get the selected customer
<script>
function getSelected() {
var cust_id = document.getElementById("cust").value;
return cust_id;
}</script>
The button, This is where I been lost. How to send this cust_id to my controller with this th:href?
<input type="button" class="button form-control btn-primary"
th:value="Next" onclick="getSelected()" th:href="#{/locate/{id}(id=${cust_id})}">
My question is how to pass cust_id as parameter?
If there is a easiest way to do this, please show me how
I had a similar situation. This is how I implemented it:
$('#cust').bind('change',function() {
var custid = $(this).children("option:selected").val();
alert("You have selected the Customer with id - " + custid);
window.location = '/myAppURL?pareaName='+ $(this).val();
});
It means to pick a value from a select (option) I had to bind it with the change event (I used JQuery). Not sure if it fits your "exact" requirement but hoping you got the idea.

Getting undefined when trying to send select value to other page

I have a small JavaScript issue.
I have the following form:
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
What I'm trying to do is to get the value from the select tag and use it in page2.
For example, is option is A, the value should be ="a".
I want to use the value="a" in page2.
document.getElementById("output"): here i want to print the result in page2.
What I've tried to do in the second page:
<script>
var select = document.getElementById("activity");
var e = select.options[select.SelectedIndex].value;
document.getElementById("output").innerHTML = e;
<!-- This doesn't show anything. -->
var test = document.getElementsbyName("activity").values;
document.getElementById("output").innerHTML = test;
<!-- The output is: function values() { [native code] } -->
var test = document.getElementsByName("activity").value;
document.getElementById("opinion").innerHTML = test;
<!-- The output is: undefined -->
</script>
So basically, getting the select element by ID or by Name doesn't work.
Getting the select element ID.value doesn't work.
Getting the select element by the index doesn't work.
Any ideas? I've literally tried anything.
Am I writing the code in the wrong place?
Do I have to send this information through the server-side?
P.S.: I am writing the app in Node.js and Express and I'm using handlebars.
Kind regards,
G.
Update:
If you want to get the value to other page, you need to fetch it from url as whole new page get rendered and your old values will not exist exist.
If you are having your values in url just fetch it by this
let url = window.location
I assume, you are trying to get the value of dropdown
select has always the value attribute to it which actually is the value you select from dropdown
You just need to look for the value of select whenever you want the selected option.
Here in your case just attach a onchange listener to select, which triggers whenever the value of select get changed
var select = document.getElementById("activity");
var mySelectValue = select.value // set the default value
select.onchange = function() {
console.log(select.value)
mySelectValue = select.value // update whenever value get changed or new value chosen
}
// Do whatever you want to do with selectvalue
<form method="get" name="basic" id="basicId" action="/page2">
<select id="activity" name="activity" class="form-control inputbox">
<option value="default" class="activities">Select value from dropdown:</option>
<option value="a" class="tests">A</option>
<option value="b" class="tests">B</option>
<option value="c" class="tests">C</option>
</select>
<button type="submit" id="searchBtn" placeholder="Search">Search</button>
</form>
So basically, I have fetched the link and I tried to check if the activity = something.
example down below:
if(url.href.indexOf("activity=a") > -1){
activity = "a"
}
document.getElementById("opinion").innerHTML = activity;
Of course, in the page2, I can see "a" as a result which is great! :)

AJAX POST Won't Work With document.getElementById Variables

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.

populate jquery form from XML

I am attempting to populate a jquery form with data from an XML where the XML has an id that will populate a dropdown in the form and upon selection of an id other form fields will be populated. BTW I will not be using PHP
My XML
<XMLReview>
<plan>
<planNumber>773</planNumber>
<Area>Upper Missouri</Area>
<ID>MISSOURI-NUT</ID>
<Name>Missouri River</Name>
<code>10030101</code>
<County>Broadwater</County>
<Station_ID>M09MISSR05</Station_ID>
</plan>
<plan>
<planNumber>774</planNumber>
<Area>Columbia</Area>
<ID>FLAT-STILL-TPA-2013</ID>
<Name>Sheppard Creek</Name>
<Description>- 3A</Description>
<code>17010210</code>
<County>Flathead</County>
<Station_ID>C09SHEPC04</Station_ID>
</plan>
</XMLReview>
The HTML
<form>
<input type="button" id="btnxml" value="XML" onclick="getXML()" />
ID <input type="text" name="ID" id="ID">
planNumber<input type="text" name="Name" id="planNumber">
area<input type="text" name="Area" id="Area">
Name: <input type="text" name="Name" id="Name">
Description: <input type="text" name="Description" id="Description">
Station ID <input type="text" name="Station_ID" id="Station_ID">
<label class="Code-label" for="code">HUC</label>
<select class="select_code" id="code" name="code" data-iconpos="left" data-icon="grid">
<option></option>
<option> 10010001</option>
<option> 10010002</option>
<option> 10020001</option>
</select>
<label class="county-label" for="County">County</label>
<select class="select_county" id="County" name="County" data-iconpos="left" data-icon="grid">
<option></option>
<option> Beaverhead </option>
<option> Big Horn </option>
<option> Blaine </option>
</select>
</form>
The script
<script>
function getXML()
{
$.get("XMLReview.xml", function(data) {
$.ajax({
type: "GET",
url: "XMLReview.xml",
dataType: "xml",
success: function (xml) {
var select = $('#ID');
$(xml).find('plan').each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected'));
var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
var value = $(this).text();
});
});
}
});
alert(data);});
}
</script>
Unfortunataly this is not working and I don't know why. Can anyone help me please
One or two things:
You are specifying the onclick event inline:
<input type="button" id="btnxml" value="XML" onclick="getXML()" />
Why not keep everything in one place -- since you already are using quite a bit of jQuery. Just add it to the javascript block like this:
<input type="button" id="btnxml" value="XML" />
and
$('#btnxml').click(function() {
getXML();
});
Without checking your javascript/ajax code, this construction is wrong:
function getXML(){
$.get("XMLReview.xml", function(data) { <<======= REMOVE
$.ajax({
type: "GET",
url: "XMLReview.xml",
dataType: "xml",
success: function (xml) {
var select = $('#ID');
$(xml).find('plan').each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected'));
var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
var value = $(this).text();
}); //END $(xml).find.eq.find.each
}); //END #ID.change
}); //END $(xml).find.each
alert(data);
} //END AJAX.success fn
}); //END $.ajax
}); //END $.get <<=================================== REMOVE
}
It should look like this:
function getXML(){
$.ajax({
type: "GET",
url: "XMLReview.xml",
dataType: "xml",
success: function (xml) {
var select = $('#ID');
$(xml).find('plan').each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected'));
var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
var value = $(this).text();
}); //END $(xml).find.eq.find.each
}); //END #ID.change
}); //END $(xml).find.each
alert(data);
} //END AJAX.success fn
}); //END $.ajax
}
The extra $.get() wrapper is unnecessary.
Note that $.ajax() and $.get() and $.post() do the same thing. You are using the more structured $.ajax() construction, which is (IMHO) easier to keep things straight.
$.get() simply hard-codes the type="GET" and $.post() hard-codes the type="POST"
Also, I haven't done much with the XML dataType, but I strongly suspect that xml -- in the success function of your AJAX code block, in this context:
success: function (xml) {
//post ajax code here, for eg.
alert(xml);
}
Is a variable that will contain whatever has been ECHOed/printed/etc from the server side script? I don't believe it's an XML object...
Ok there are kind of a lot of things going on here so I figured a fresh implementation would be easier to understand than a series of corrections (I'll try and note places where your understanding of JavaScript might need some work) First a demo. Now the JavaScript:
$('#btnxml').on('click', function() {
var select = $('#ID'),
xml = $($.parseXML($('#XMLData').text())),
plans = xml.find('plan');
plans.each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
});
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected')),
plan = $(plans[selectedIndex]);
$('#planNumber').val(plan.find('planNumber').text());
$('#Area').val(plan.find('Area').text());
$('#Name').val(plan.find('Name').text());
$('#Description').val(plan.find('Description').text());
$('#Station_ID').val(plan.find('Station_ID').text());
$('#code').val(plan.find('code').text());
$('#County').val(plan.find('County').text());
}).trigger('change');
});
And then the HTML
<script type='text/xml' id='XMLData'>
<XMLReview>
<plan>
<planNumber>773</planNumber>
<Area>Upper Missouri</Area>
<ID>MISSOURI-NUT</ID>
<Name>Missouri River</Name>
<code>10030101</code>
<County>Broadwater</County>
<Station_ID>M09MISSR05</Station_ID>
</plan>
<plan>
<planNumber>774</planNumber>
<Area>Columbia</Area>
<ID>FLAT-STILL-TPA-2013</ID>
<Name>Sheppard Creek</Name>
<Description>- 3A</Description>
<code>17010210</code>
<County>Flathead</County>
<Station_ID>C09SHEPC04</Station_ID>
</plan>
</XMLReview>
</script>
<form>
<input type="button" id="btnxml" value="XML" /><br/>
ID <select type="text" name="ID" id="ID"></select><br/>
planNumber<input type="text" name="Name" id="planNumber"><br/>
area<input type="text" name="Area" id="Area"><br/>
Name: <input type="text" name="Name" id="Name"><br/>
Description: <input type="text" name="Description" id="Description"><br/>
Station ID <input type="text" name="Station_ID" id="Station_ID"><br/>
<label class="Code-label" for="code">HUC</label>
<select class="select_code" id="code" name="code" data-iconpos="left" data-icon="grid">
<option></option>
<option>10010001</option>
<option>10010002</option>
<option>10020001</option>
<option>10030101</option>
<option>17010210</option>
</select>
<br/>
<label class="county-label" for="County">County</label>
<select class="select_county" id="County" name="County" data-iconpos="left" data-icon="grid">
<option></option>
<option>Beaverhead</option>
<option>Big Horn</option>
<option>Blaine</option>
</select>
</form>
First, I made these changes to make this easier to demonstrate in JSFiddle, but they don't necessarily match what your final code will be:
I faked the AJAX request (the other answer here gives you a clear explanation of how to properly use jQuery's excellent AJAX helper methods). When rolling this answer into yours you can just assume that all of this is wrapped in a $.get() that fetches your XML remotely.
I also bound the click handled in JavaScript to $('#btnxml') (this is cleaner, but also because JSFiddle doesn't like onclick attributes that point to named functions), this is not strictly wrong it's just cleaner.
Now for the substantive changes:
You are really trying to do two things, populate your $('#ID') selector (which was originally a <input type='text'> which is incorrect, in this code I updated to to a <select>, and then after it's populated you are trying to bind a change event handler. You had these steps inside each other, and I separated them back out. Also programmaticly changing a <select> doesn't trigger a change event automatically, so I appended a .trigger('change') at the end.
It also appears that you are attempting to take the child nodes of the selected plan and update the corresponding input with the same name. You could use the .childNodes property but this will include TextNodes for all of the white-space between XML nodes, and rather than trying to filter them out I thought it would be cleaner to just map them individually. This may not work for you if your HTML and XML are constantly being updated but the next point I'm going to make possibly would prevent a totally automatic approach anyways.
Selecting an option based on a value presents some challenges. jQuery is very smart. If you have a <select> element with a set of options that don't have value attributes and you try and set that <select> element's .val() by a string of one of those <option>s inside that element it will do the right thing. However if there are no elements that match that value then it will silently pass over it. Your XML has code and County values that do not appear in your HTML. I added the missing code values to show you that it is working, but I didn't add them to the County <select>. If you know all of your possible codes and county's and you can update your HTML then this won't be a problem, if instead you want new values to be appended while old values are just selected, then your code will get a little trickier.

How to structure the code to process multiple variables from mulitple form elements in JavaScript and remember the choices?

E.g. I have an HTML form:
<form role="search" method="get" id="searchform" action="" >
<!-- DIRECT SEARCH INPUT TO SEARCH STRING -->
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
<!-- DROPDOWN TO SELECT ONE CHOICE -->
<select name='country' id='country' class='postform' >
<option class="level-0" value="2">USA</option>
<option class="level-0" value="3">Canada</option>
<option class="level-0" value="4">Mexico</option>
<option class="level-0" value="5">Cuba</option>
</select>
<!-- CHECKBOXES TO SELECT MULTIPLE CHOICES -->
<div id="color">
<input type="checkbox" name="" value="21" />Beachfront
<input type="checkbox" name="" value="16" />TV
<input type="checkbox" name="" value="20" />Internet
<input type="checkbox" name="" value="17" />Pets Allowed
</div>
</form>
<div id="results"><!-- THE AJAX RESULTS GOES HERE --></div>
And I want to be able to make AJAX request every time the user:
1) write something in the search input box and click search button
OR
2) select one choice from the dropdown menu
OR
3) select one or multiple choices from the checkboxes that are checked
The problem is that I don't know how to structure my JavaScript code correctly and what is the best way to remember and manage choices that the user selected before, to take all things in account. For example, not just the search term when he write something and click search button, but also to take in count the dropdown choice (probably done one step before) and maybe the checked options from checkboxes if he has checked something before. Here is what I have so far:
jQuery(document).ready(function($){
// RESULTS SHOULD APPEAR IN #results DIV AFTER AJAX IS DONE
var $maincontent = $('#results');
// SEARCH INPUT PROCESSING
$('#searchsubmit').click(function(e){
e.preventDefault();
var searchval = $('#s').val();
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
searchval : searchval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
}
);
});
// COUNTRY DROPDOWN CHOICE PROCESSING
$('#country').on('change', function() {
var countryval = this.value;
$maincontent.animate({ opacity : '0.1' })
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
countryval : countryval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
$maincontent.animate({ opacity : '1' })
}
);
return false;
});
// CHECKBOXES PROCESSING
$('#color input[type=checkbox]').click(function() {
if (this.checked) {
// code if checked
}
else {
// nothing
}
});
});
As you can see, it's very bad. Because one "function" checks only click, one change and I don't know how to grab values from the checkboxes and make an array and send it via ajax ;(.
Any idea how to structure the JavaScript code so it is not so separated and the checks are somehow in one part (or more logical) instead of three separated parts?
Any ideas are welcome.
Create som logic :
var _do = {
bind: function() {
var self = this;
$('#searchsubmit').on('click', function(e){
e.preventDefault();
self.ajax('searchval', $('#s').val());
});
$('#country').on('change', function() {
self.ajax('countryval', this.value);
});
return self;
},
ajax: function(key, value) {
var data = {action: 'ajax_search_action_do'};
data[key] = value;
$.post(
WPaAjax.ajaxurl, data, function( response ) {
$maincontent.empty().append( response );
}
);
}
}
jQuery(document).ready(function($){
_do.bind();
});
Maybe use jquery.form.js?
http://malsup.com/jquery/form/
It's a great plugin, just structure the form like it was a normal redirection form, add array in name of checkboxes
<input type="checkbox" name="types[]" value="21" />Beachfront
Add target URL to the form, and then...
When u want to submit the form just do
$('searchform').ajaxSubmit({
success: function() {
// callback
}
)
Trigger this on checkboxes change, dropdown change etc. To make the code clean, use one selector
$('#country, #s, #color input').on('change', sendAjaxForm);

Categories

Resources