Get select box value to use as a variable - javascript

I'm hoping someone can help, I'm a relative newbie to javascript and have the following issue. I have a select box with id "mySelect"
that is populated with the following code -
$(document).ready(function(artists){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success: function(artists_list) {
var select = $('#mySelect');
var artistsArr = [];
$(artists_list).find('vw_ADM_BookingListNull[strArtistName]').each(function(){
var artists = $(this).attr('strArtistName');
if ($.inArray(artists, artistsArr) == -1) {
select.append('<option value="'+artists+'">'+artists+'</option>');
artistsArr.push(artists);
}
});
select.children(":first").text("please make a selection").attr("selected",true);
}
});
});
I need to use the selected value as a variable to insert into another piece of code. How do I make a variable from this?
The variable will be used in place of
'vw_ADM_BookingListNull[strArtistName="James Zabiela"]'
in the following code which populates a table from an xml list.
$(document).ready(function(unavailable){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success:(function(unavail){
$(unavail).find('vw_ADM_BookingListNull[strArtistName="James Zabiela"]').each(function() {
var venue = $(this).attr('strVenueName');
var artist = $(this).attr('strArtistName');
var booking_date = $(this).attr('dteEventDate').substr(0,10); //subtr strips date down
if(!(booking_date >= $nowformat && booking_date <= $advformat)){
$('<tr style="display:none;"></tr>')
}
else {
$('<tr></tr>').html('<th>'+booking_date+'</th><td>'+artist+'</td>').appendTo('#unavail');
}
});
})
});
});
I need to handle the possible event that a value has not been selected and so the value of the select box will be "please make a selection", which is set as the default value.
So I guess I need to wrap some kind of if statement around the code that creates the table, so as to not display anything if nothing has yet been selected.
Any help would be massively appreciated as deadlines are looming.
Thanks again.

You appear to be using jQuery, so from the jQuery Documentation
var dropdownValue = $('#mySelect').val();

Related

Value posts firstly and then only it finishes input (if clicked). needed backwards(code is corect)

I have dropdown list of country suggestions and input above. When i click on one of them - AJAX should work(and it does) and add value to #msg_native. HTML:
echo '<div class="search_native"><input type="text" name="native_input" id="native"/>';
echo "<div id='output'></div></div>";
All JQUERY :
<script type="text/javascript">
$(document).ready(function() {
$("input").keyup(function(){
$array = ['usa','france','germany'];
$input_val = $("input[name='native_input']").val();
$('#output').text('')
r = new RegExp($input_val)
for (i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>')
}
}
});
$(document).on('click', '.match', function(){
$value = $(this).text();
$('#native').val($value);
});
});
</script>
<script type="text/javascript">
$(function() {
$('#native').change(function() {
alert('cl');
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: {native_input: $("input[name='native_input']").val()},
cache: false,
success: function(data){
alert(data);
$("#msg_native").after(data);
}});
return false;
});
});
</script>
The problem is that the value that gets posted is only what Ive typed myself, regardless on clicked element. But I want complete value- not only typed letters...so it firstly posts value and then 'finishes' the input (if clicked)
What can you practically advice to me?
data: {native_input: $value},
returns empty string
Some of this might be debatable but I put those in place for maintainability of the code and/or to match the most recent jQuery.
Only use one document ready handler (if possible)
Remove all the global objects (put var in front of them)
Use the native id when possible as fastest selector (not $("input[name='native_input']") for instance)
use this in the event handler, not the full selector (see next item)
If I enter "France" not "france" match does not work so need to case that input to equality var $input_val = $(this).val().toLowerCase();
You start with an empty field, might be good to show the match for that - simply trigger the keyup on startup to show all the array: }).trigger('keyup'); Now they are available for your clicking.
Attach the click handler on the wrapper for the "match" elements: $('#output').on('click', '.match', function() {
Use the promise form of the ajax .done(
Create a new custom event instead of the "change" on the native. We can then trigger that event as/when needed (the real issue you describe) Example: $('#native').trigger('myMatch'); and as I use it here:
trigger the event on a full match:
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
Revised code:
$(document).ready(function() {
$("#native").on('keyup', function() {
var $array = ['usa', 'france', 'germany'];
var $input_val = $(this).val().toLowerCase();
$('#output').html('');
var r = new RegExp($input_val);
for (var i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>');
}
}
// full match entered, trigger the match
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
}).on('myMatch', function() {
alert('cl');
var nativeMatch = {
native_input: $("#native").val()
};
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: nativeMatch,
cache: false
}).done(function(data) {
alert(data);
$("#msg_native").after(data);
});
return false;
}).trigger('keyup');
$('#output').on('click', '.match', function() {
var $value = $(this).text();
$('#native').val($value).trigger('myMatch');
});
});

jQuery updates DOM, browser does not

I am working on a project where for example field number 3 on the webpage should be updated with values from a database when a user enters data into field number 1. This already works fine without any problems.
But if the user modifies field number 3 first and field number 1 at a later time, just the DOM gets updated (as I can tell from Firebug) but there isn't any visible change on field number 3 to the user.
I created a very basic version of this problem and still I am not able to tell what's wrong here.
HTML
<div id="container1">
<textarea id="container1.1">Entry 1.1</textarea>
<textarea id="container1.2">Entry 1.2</textarea>
<textarea id="container1.3">Entry 1.3</textarea>
</div>
jQuery
$(document).ready(function() {
$('textarea').change(function() {
var clickedObject = $(this);
var id = $(this).attr('id').substr(9);
var value = $(this).val();
var dataString = "id=" + id + "&value=" + value;
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
cache: false,
success: function(Result)
{
if(Result == '-')
{
console.log('Nothing to do');
} else {
clickedObject.next().next().html(Result);
}
}
});
});
});
PHP
<?php
if ($_POST['id'] == '1.1') {
echo 'Modified string';
} else {
echo '-';
}
?>
You must set values of textarea by .val() method, instead of html().
And maybe it will be more descriptive if you will use only one id of textarea that should call request on changes.

jQuery Ajax placing random "jQuery111201xxx" into string

I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});

Javascript works fine with a hard-coded string but not with variable

I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});

How can I capture the attribute id from a dynamically generated html?

I am pretty sure this is not so complicated but I have been for hours trying to figure out how to catch the id of this dynamically generated anchor tags.
What I do in my code is that everytime a text input changes, theres an ajax request that goes to a php file and returns me a json array with the prices then I render this results of search in buttons that will be clickable to do other types of request but so far here's where I'm stuck.
heres's the code that loops through the array and renders this buttons (NOTE:The Id of the buttons are variables rendered by the function too.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
success: function(data){
$('#loader_s').hide();
var jsarray = JSON.parse(data);
var length = jsarray.length;
for(i=0;i<jsarray.length;i++){
var index1 = i;
var index2 = Number(i++) + 1;
var index3 = Number(i++) + 2;
$('#modal-bod').append('<a onclick="renderProds();" class="btn btn-default-item prod_sel" style="margin-top:10px;" id="'+index3+'" data-dismiss="modal">'+jsarray[index1]+' <span class="pull-right" st>lps. '+jsarray[index2]+'</span></a>');
}
}
Then here's the function renderProds()
function renderProds(){
var id = $(this).attr('id');
alert(id);
}
the alert is just to try and catch the values for testing purposes, but what really goes there is another Ajax request.
The only thing I get here is that the var Id is undefined...
You can pass object like
function renderProds(obj) {
var id = obj.id;
alert(id);
}
Pass invoker object like
onclick="renderProds(this);"
I would do :
onclick="renderProds(this);"
function renderProds(that){
var id = that.id;
alert(id);
}
You use jQuery.. so USE jQuery !
Ajax can do the JSON.parse for you with just dataType: "json".
The inline onclick is bad practice.
Move the success function to make your code more readable.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
dataType : 'json',
success: productsUpdate
});
function renderProds(event){
var id = $(event.target).attr("id");
alert("Id is:"+id);
}
function productUpdate(data){
$('#loader_s').hide();
for(i=0;i<data.length;i++){
var link = $('<a>....</a>');
link.click(renderProds);
$('#modal-bod').append(link);
}
}
Now, this is readable.
Complete the link creation with your code, without the onclick, remove the inline css and use a real css selector and finally, check this ugly Number(i++)+ .... it looks so bad.

Categories