I would like to have two different textboxes, autocomplete the second textbox based on the first textbox results.
For instance, in textbox 1 start typing "un" and all the countries that start with "un" will automatically appear, select united states, in the second textbox start typing "m" and only states within the united states that start with "m" will automatically appear.
My JS files:
var suggest = {
instance : {}, // attached instances
focus : null, // current text field in focus
attach : function (opt) {
// suggest.attach () : attach autosuggest to input field
// opt : options
// - target : ID of target input field, required
// - url : Target URL to fetch suggestions, required
// - delay : Delay before autocomplete fires up, optional, default 500ms
// - min : Minimum characters to fire up autocomplete, default 2
// Create autocomplete wrapper and box
var id = Object.keys(suggest.instance).length,
input = document.getElementById(opt.target);
input.outerHTML = "<div id='acWrap" + id + "' class='acWrap'>" + input.outerHTML + "<div id='acBox" + id + "' class='acBox'></div></div>";
// Set the HTML references and options
suggest.instance[opt.target] = {
input : document.getElementById(opt.target),
wrap : document.getElementById("acWrap" + id),
box : document.getElementById("acBox" + id),
delay : opt.delay ? opt.delay : 500,
url : opt.url,
min : opt.min ? opt.min : 2,
timer : null
};
// Attach key listener
suggest.instance[opt.target].input.addEventListener("keyup", function (evt) {
// Clear old timer
if (suggest.instance[opt.target].timer != null) {
window.clearTimeout(suggest.instance[opt.target].timer);
}
// Hide and clear old suggestion box
suggest.instance[opt.target].box.innerHTML = "";
suggest.instance[opt.target].box.style.display = "none";
// Create new timer, only if minimum characters
if (evt.target.value.length >= suggest.instance[opt.target].min) {
suggest.instance[opt.target].timer = setTimeout(
function () { suggest.fetch(evt.target.id); },
suggest.instance[opt.target].delay
);
}
});
// This is used to hide the suggestion box if the user navigates away
suggest.instance[opt.target].input.addEventListener("focus", function (evt) {
if (suggest.focus != null) { suggest.close(null, true); }
suggest.focus = opt.target;
});
},
fetch : function (id) {
// suggest.fetch() : AJAX get suggestions and draw
// id : ID of target input field, automatically passed in by keyup event
var req = new XMLHttpRequest();
req.addEventListener("load", function () {
var data = JSON.parse(this.response);
if (data.length > 0) {
data.forEach(function (el) {
suggest.instance[id].box.insertAdjacentHTML("beforeend", "<div onclick=\"suggest.select('" + id + "', this);\">" + el + "</div>");
});
suggest.instance[id].box.style.display = "block";
document.addEventListener("click", suggest.close);
}
});
req.open("GET", suggest.instance[id].url + "?term=" + suggest.instance[id].input.value);
req.send();
},
select : function (id, el) {
// suggest.select() : user selects a value from autocomplete
suggest.instance[id].input.value = el.innerHTML;
suggest.instance[id].box.innerHTML = "";
suggest.instance[id].box.style.display = "none";
document.removeEventListener("click", suggest.close);
},
close : function (evt, force) {
// suggest.close() : close the autocomplete box if the user clicks away from the input field
// evt : click event
// force : force close
if (force || event.target.closest(".acWrap") == null) {
suggest.instance[suggest.focus].box.innerHTML = "";
suggest.instance[suggest.focus].box.style.display = "none";
document.removeEventListener("click", suggest.close);
}
}
};
I thought it would simple update the GET term
I created two different js files and updated the term line.
autocompletecountry.js
req.open("GET", suggest.instance[id].url + "?termco=" + suggest.instance[id].input.value);
autocompletestate.js
req.open("GET", suggest.instance[id].url + "?termst=" + suggest.instance[id].input.value);
My search.php files
<?php
// CONNECT TO DATABASE
$host = '11.22.33.44';
$dbname = 'dbname';
$user = 'dbuser';
$password = 'PASSWORD';
$charset = 'utf8';
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=$charset", $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
// SEARCH AND OUTPUT RESULTS
$stmt = $pdo->prepare("select distinct country FROM locationtbl WHERE country LIKE ?");
$stmt->execute(["%" . $_GET['term'] . "%"]);
$data = [];
while ($row = $stmt->fetch(PDO::FETCH_NAMED)) {
$data[] = $row['country'];
}
$pdo = null;
echo json_encode($data);
?>
I created two different search files and updated the term line.
searchcountry.php
$stmt->execute(["%" . $_GET['termco'] . "%"]);
searchstate.php
$stmt->execute(["%" . $_GET['termst'] . "%"]);
Now what is happening is when I start typing in textbox 1 all countries are listed. however when I go to
example.com/searchcountry.php?termco=un
It will only show countries with 'un' in the name.
source: https://code-boxx.com/autocomplete-javascript-php-mysql/
My index.php
<!DOCTYPE html>
<html>
<head>
<link href="autocomplete.css" rel="stylesheet">
<script src="autocompletecountry.js"></script>
<script src="autocompletestate.js"></script>
<script>
/* [INIT - ON WINDOW LOAD] */
window.addEventListener("load", function(){
suggest.attach({
target : "inputA",
url : "http://example.com/searchcountry.php"
});
suggest.attach({
target : "inputB",
url : "http://example.com/searchstate.php",
delay : 200,
min : 3
});
});
</script>
</head>
<body>
<input type="text" id="inputA"/>
<br>
<input type="text" id="inputB"/>
</body>
</html>
Figure out what I had to do.
The page will only work properly with 1 autocomplete.js file
I had to edit the autocomplete.js like below
if (document.getElementById("inputB").value == '' && document.getElementById("inputC").value == '') {
req.open("GET", suggest.instance[id].url + "?term=" + suggest.instance[id].input.value);
req.send();
} else if (document.getElementById("inputC").value == '') {
req.open("GET", suggest.instance[id].url + "?cou=" + document.getElementById("inputA").value + "&term=" + suggest.instance[id].input.value);
req.send();
} else if (document.getElementById("inputA").value != '' && document.getElementById("inputB").value == '') {
req.open("GET", suggest.instance[id].url + "?cou=" + document.getElementById("inputA").value + "&term=" + suggest.instance[id].input.value);
req.send();
} else {
req.open("GET", suggest.instance[id].url + "?cou=" + document.getElementById("inputA").value + "&sta=" + document.getElementById("inputB").value + "&term=" + suggest.instance[id].input.value);
req.send();
}
},
This will allow for 3 autocomplete boxes reliant on the first textbox.
Related
I have Javascript function returning an object with an HTMLHtmlElement object I'd like to parse:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://someothersite.com/widgets/whatson.js"></script>
<script src="https://someothersite.com/widgets/jquery-deparam.js"></script>
<script>
var configuration = {
schedule: 'now'
};
if ( window.location.search ) configuration = $.extend({}, configuration, $.deparam( (window.location.search).replace('?','') ));
$(function(){
var content = $('div#output').whatsOn( configuration );
console.log( $("div#output").html() );
});
</script>
The above whatsOn function fills my output div with the HTML content returned, but the console log outputs nothing. If I write content to the console, it is an init object with data I'd like to parse. If I add the following, it sends an [object HTMLHtmlElement] to the console with all the data to the console:
var html = content.context.childNodes[1];
console.log( html );
How can I parse that the HTML? What I am after is the innerText element of the html variable above. However, if I change to content.context.childNodes[1].innerText, I get nothing.
UPDATED
Here is the code pasted:
/**
* Source for the Daily and Weekly Widgets
* Both of these widgets are rendered via the custom whatsOn Jquery plugin which is implemented via this script
*/
;
(function ($, window, document, undefined) {
/*
=== Begin async caching functions ===
Asynchronous Caching Code
The below code seems to be a direct copy of the code from https://learn.jquery.com/code-organization/deferreds/examples/
This code ensures that multiple requests are not made for loading the same data/resource.
Generic cache factory (below)
One promise is cached per URL.
If there is no promise for the given URL yet, then a deferred is created and the request is issued.
If it already exists, however, the callback is attached to the existing deferred.
*/
$.cacheFactory = function (request) {
var cache = {};
return function (key, callback) {
if (!cache[ key ]) {
cache[ key ] = $.Deferred(function (defer) {
request(defer, key);
}).promise();
}
return cache[ key ].done(callback);
};
};
// Every call to $.cacheFactory will create a cache respository and return a cache retrieval function
$.template = $.cacheFactory(function (defer, url) {
$.ajax({
url: url,
data: $.template.params,
dataType: 'jsonp',
success: defer.resolve,
error: defer.reject,
complete: defer.always
});
});
// === End async caching functions
// This function handles rendering template markup and data
$.renderTemplate = function (data, elem, options) {
var label = ( !options.label ) ? elem.addClass('whatson-hidden') : '';
return elem.empty().append(data) && label;
};
// Handles error message display
$.errorMessage = function (elem) {
return elem.append('error');
};
/*
=== Begin .whatsOn plugin functions ===
The following functions create a jquery plugin which can be executed on a JQuery element to render the whatson widget
The .whatsOn() functions are added to $.fn in order to create this plugin
- see https://learn.jquery.com/plugins/basic-plugin-creation/
*/
$.fn.whatsOn = function (options) {
// Do not initialize the widget if it has already been initialized, or if the station param is missing
if (this.data('whatson-init') || !options.station) {
return;
}
this.data('whatson-init', true); // widget-initialized flag
options = $.extend({}, $.fn.whatsOn.options, options);
// Force fix the old widget calls that do not use iframes.
if (options.env == 'http://composer.nprstations.org') options.env = 'https://api.composer.nprstations.org/v1';
$.fn.whatsOn.env = options.env;// Determines which API request URL to use
// Add CSS stylesheet
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('type', 'text/css');
css.setAttribute('href', options.assets + '/widgets/css/v2.css');
document.getElementsByTagName('head')[0].appendChild(css);
/*
Return the plugin object
When you filter elements with a selector ($('.myclass')), it can match more than only one element.
With each, you iterate over all matched elements and your code is applied to all of them.
*/
return this.each( function () {// BEGIN Return the plugin.
var elem = options.elem = $(this);
var ucs = options.station;
var schedule = options.schedule;
var times = options.times;
var next = options.next;
var show_song = options.show_song || null;
var display_style = options.style || null;
var request_url;
// The buy links
var hide_itunes = options.hide_itunes || null;
var hide_amazon = options.hide_amazon || null;
var hide_arkiv = options.hide_arkiv || null;
if (!options.affiliates) options.affiliates = {};
if (options.itunes) options.affiliates.itunes = options.itunes;
if (options.amazon) options.affiliates.amazon = options.amazon;
if (options.arkiv) options.affiliates.arkiv = options.arkiv;
elem.addClass('whatson-wrap');// Add widget class
$("body").attr('id', 'nprds_widget'); // Add an ID to the body of the document
// Ensure that the moment() JS plugin is available, if not, then add and load it (http://momentjs.com/docs/)
if (!window.moment) {
$.getScript('https://composer.nprstations.org/widgets/js/moment.isocalendar.js').done(function (script) {
builder();// Build plugin function (see below)
});
} else {
builder();// Build plugin function (see below)
}
// This function builds the plugin, it does all of the setup required
function builder() {// BEGIN build plugin function
// Set the date/range for the widget header. If its the daily widget use a date, for the weekly widget use a range
var req_date = ( options.schedule === 'week' )
? moment().isoday(1).format('YYYY-MM-DD') + ',' + moment().isoday(7).format('YYYY-MM-DD')
: moment().format('YYYY-MM-DD');
request_url = $.fn.whatsOn.env + '/widget/' + ucs + '/' + schedule;
$.template.params = {
format: 'jsonp',
date: req_date,
times: times,
show_song: show_song || null,
style: display_style || null,
hide_itunes: hide_itunes || null,
hide_amazon: hide_amazon || null,
hide_arkiv: hide_arkiv || null,
itunes: options.affiliates.itunes || null,
amazon: options.affiliates.amazon || null,
arkiv: options.affiliates.arkive || null
};
// Pull out empty fields
if (!$.template.params.itunes) delete $.template.params.itunes;
if (!$.template.params.amazon) delete $.template.params.amazon;
if (!$.template.params.arkiv) delete $.template.params.arkiv;
if (!$.template.params.show_song) delete $.template.params.show_song;
if (!$.template.params.style) delete $.template.params.style;
if (!$.template.params.hide_itunes) delete $.template.params.hide_itunes;
if (!$.template.params.hide_amazon) delete $.template.params.hide_amazon;
if (!$.template.params.hide_arkiv) delete $.template.params.hide_arkiv;
// force now playing to an uncached request
if (schedule === 'now') request_url = request_url + '?bust=' + ~~(Math.random() * 1E9);
/*
$.template(request_url) = Request widget data (from cache or a new request), uses cacheFactory (see code at the top of this script)
When the data has been received, handle the construction and rendering of the HTML
*/
$.when( $.template(request_url) ).done( function (data) {
$.renderTemplate(data, elem, options);
// Set up the widget header
if (schedule === 'week') {
var week_of = moment().isoday(1).format('[Week of] MMMM Do, YYYY');
$.fn.whatsOn.header(elem, week_of, options);
}
if (schedule === 'day') {
var day_date = moment().format('dddd, MMMM Do, YYYY');
$.fn.whatsOn.header(elem, day_date, options);
}
// Add a handler for when an Itunes link is clicked
$('.itunes-link').on('click', function (e) { // BEGIN itunes link click handler
e.preventDefault();// If this method is called, the default action of the event will not be triggered.
var searchUrl = $(this).attr('href').split('?');
var forwardTo = '';
var searchPairs = searchUrl[1].split('&');
var searchTerms = '';
var affiliate = '';
$.each(searchPairs, function (key, value) {
var pairs = value.split('=');
if (pairs[0] == 'at') {
affiliate = pairs[1];
}
else {
searchTerms = searchTerms + ' ' + pairs[1];
}
});
$.ajax({
url: 'https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?entity=musicTrack&country=US&term=' + searchTerms + '&at' + affiliate + '&limit=1&callback=?',
type: 'GET',
dataType: 'jsonp',
success: function (data) {
console.log('data', data)
if (data.resultCount > 0) {
if (data.results[0].collectionViewUrl) {
forwardTo = data.results[0].collectionViewUrl;
}
else {
forwardTo = data.results[0].artistViewUrl;
}
}
else {
forwardTo = 'https://itunes.apple.com/us/';
}
window.open(forwardTo, 'itunes');
},
error: function (err) {
console.log('err', err);
console.log(err);
window.open('https://itunes.apple.com/us/', 'itunes');
}
});
});// END itunes link click handler
$.fn.whatsOn.collapse();
}).always(function () {
if (schedule === 'now') {
setTimeout(builder, 60000);
}
}).fail(function () {
$.errorMessage(elem);
});
}// END build plugin function
});// END return the plugin
};
// Expand/collapse episode detail - This widgets allows for you to expand an episode to view it's playlist and episode notes.
$.fn.whatsOn.collapse = function () {
$('.playlist-controls').on('click.whatsOn', function () {
$(this).toggleClass('opener');
$(this).parent().find('.dailyPlaylist').toggle();
});
$('.notes-controls').on('click.whatsOn', function () {
$(this).toggleClass('opener');
$(this).parent().find('.episodeNotes').toggle();
});
};
// Construct header and setup events handler for the next/previous link
$.fn.whatsOn.header = function (elem, date, options) {
var nav_control_prev = '<td class="whatson-prev arrow-left"><a class="hidden" href="#">Previous</a></td>';
var nav_control_next = '<td class="whatson-next arrow-right"><a class="hidden" href="#">Next</a></td>';
var header_nav = [
'<table id="whatson-header" width="100%" border="0" cellspacing="0" cellpadding="0">',
'<tr>' + nav_control_prev + '<td class="whatson-date">' + date + '</td>' + nav_control_next + '</tr>',
'</table>'
].join('');
elem.prepend(header_nav);
// Events handler for navigational next/previous links
$(elem).find('.whatson-prev, .whatson-next').on('click', options, $.fn.whatsOn.nav);
};
// This is the event handler for the widget's next/previous links
$.fn.whatsOn.nav = function (e) {// BEGIN next/previous date/date-range handler
e.preventDefault();
var widget = e.data.elem;
var header = '.whatson-header';
var date_header = '.whatson-date';
var content = '.whatson-content';
var direction = ( $(e.currentTarget).is('.whatson-next') ) ? 'next' : 'prev';
var current_date = widget.find(date_header).text();
var moment_date = moment(current_date, 'dddd, MMMM D YYYY');
var station = e.data.station;
var schedule = e.data.schedule;
var affiliates = e.data.affiliates;
var full_week_date = current_date.replace('Week of ', '');
var request_url;
var options = {}; // Configuration
// Configure buy links for songs within episodes
if (affiliates.itunes) options.itunes = affiliates.itunes;
if (affiliates.amazon) options.amazon = affiliates.amazon;
if (affiliates.arkiv) options.arkiv = affiliates.arkiv;
if (e.data.hide_itunes) options.hide_itunes = e.data.hide_itunes;
if (e.data.hide_amazon) options.hide_amazon = e.data.hide_amazon;
if (e.data.hide_arkiv) options.hide_arkiv = e.data.hide_arkiv;
if (e.data.show_song) options.show_song = e.data.show_song;// Display song meta data
if (e.data.style) options.style = e.data.style;// Which template is being used
// This function updates the display after a new request is made
var updater = function (request_url, update_header) {
$('.opener, .closer').off('.whatsOn'); // Disable event handlers
$.when( $.template(request_url) ).done( function (data) { // After the request, update the display
widget.find(header)
.remove().end()
.find(date_header).html(update_header).end()
.find(content).replaceWith(data);
$.fn.whatsOn.collapse();
});
};
if (direction === 'next') { // The 'next' link was clicked
var next_from_current = moment(full_week_date, 'MMMM D YYYY').add('d', 7);
// Set the next date/date-range. If its the daily widget use a date, for the weekly widget use a range
var next_api = ( schedule === 'week' )
? '?date=' + next_from_current.isoday(1).format('YYYY-MM-DD')
+ ',' + next_from_current.isoday(7).format('YYYY-MM-DD')
: '?date=' + moment_date.add('d', 1).format('YYYY-MM-DD');
var next_header = ( schedule === 'week' )
? moment(next_from_current, 'MMMM D YYYY').isoday(1).format('[Week of] MMMM Do, YYYY')
: moment_date.format('dddd, MMMM Do, YYYY');
request_url = $.fn.whatsOn.env + '/widget/' + station + '/' + schedule + next_api;
$.template.params = $.extend({ format: 'jsonp' }, options);
updater(request_url, next_header);// Go ahead and update the display to be the 'next' date/date-range
} else {
// Set the previous date/date-range. If its the daily widget use a date, for the weekly widget use a range
var prev_from_current = moment(full_week_date, 'MMMM D YYYY').subtract('d', 7);
var prev_api = ( schedule === 'week' )
? '?date=' + prev_from_current.isoday(1).format('YYYY-MM-DD')
+ ',' + prev_from_current.isoday(7).format('YYYY-MM-DD')
: '?date=' + moment_date.subtract('d', 1).format('YYYY-MM-DD');
var prev_header = ( schedule === 'week' )
? moment(prev_from_current, 'MMMM D YYYY').isoday(1).format('[Week of] MMMM Do, YYYY')
: moment_date.format('dddd, MMMM Do, YYYY');
$.template.params = $.extend({ format: 'jsonp' }, options);
request_url = $.fn.whatsOn.env + '/widget/' + station + '/' + schedule + prev_api;
updater(request_url, prev_header);// Go ahead and update the display to be the 'previous' date/date-range
}
};// END next/previous date/date-range handler
// Default widget options
$.fn.whatsOn.options = {
schedule: 'now',
label: true,
env: 'https://api.composer.nprstations.org/v1',
assets: 'https://composer.nprstations.org',
affiliate: {},
times: true,
next: true
};
// === End .whatsOn plugin functions ===
})(jQuery, window, document);
I have a jQuery function which execute when page is post back by using back button. But the dropdown value does not change when page is post back in the older version of Firefox. In older version it is just showing the default values when page is post back. Below is the jQuery function:
function loadData() {
try {
var URL = "/Home/LoadBackdata/" + new Date().getMilliseconds();
$.post(URL, null, function (data) {
debugger;
if (data != "") {
var backData = data.split(",");
if (backData[0] != "") {
$('#ConsignorAddressCountryId option').removeAttr('selected');
// [1]
$("#ConsignorAddressCountryId option[value=" + backData[0] +").prop('selected', true);
//ConsigneeAddressCountryId is the id of another class which consist of a dropdown
$('#ConsigneeAddressCountryId option').removeAttr('selected');
$("#ConsigneeAddressCountryId option[value=" + backData[3] +").prop('selected', true);
$('#drpQuantity option').removeAttr('selected');
$('#drpQuantity').prop('selectedIndex', ((parseInt(backData[13]) == 0) ? 0 : (parseInt(backData[13]) - 1)));
}
}
});
[1] is where I am removing the default selected value - ConsignorAddressCountryId is the id of the class which consist of a dropdown.
I have also tried some things. Below is the code:
function loadData() {
try {
var URL = "/Home/LoadBackdata/" + new Date().getMilliseconds();
$.post(URL, null, function (data) {
debugger;
if (data != "") {
var backData = data.split(",");
if (backData[0] != "") {
$('#ConsignorAddressCountryId option').removeAttr('selected');
$("#ConsignorAddressCountryId").find('option:Selected').removeAttr("selected");
document.getElementById('ConsignorAddressCountryId').selectedIndex = -1;
var ttt = $("#ConsignorAddressCountryId option[value=" + backData[0] + "]").text();
$("#dvQuoteFrom >div >a >span >.selectBox-label").first().text("ttt");
$("#ConsignorAddressCountryId option[value=" + backData[0] + "]").prop('selected', true);
$('#ConsigneeAddressCountryId option').removeAttr('selected');
document.getElementById('ConsigneeAddressCountryId').selectedIndex = -1;
var Consignee = $("#ConsigneeAddressCountryId option[value=" + backData[0] + "]").text();
$("#dvQuoteTo >div >a >span >.selectBox-label").first().text(Consignee);
$("#ConsigneeAddressCountryId option[value=" + backData[3] + "]").prop('selected', true);
$("#drpQuantity").find('option:Selected').removeAttr("selected");
document.getElementById('drpQuantity').selectedIndex = -1;
var Quantity = $("#drpQuantity option[value=" + backData[13] + "]").text();
$("#divQuantity>a >span >.selectBox-label").first().text(parseInt(10));
$('#drpQuantity').prop('selectedIndex', ((parseInt(backData[13]) == 0) ? 0 : (parseInt(backData[13]) - 1)));
}
}
});
But it still nor working in older versions of Firefox.
Try to use reset function like to remove selected :
$('#yourdropdownid').reset();
And to set selected value, you can user val() like :
$('#yourdropdownid').val(your value);
I'm trying to add an "onclick" event with their respective function from js JQuery to an interactive table td I'm doing in another .php file, the problem is not executed in the place where I want to do it but if the same instruction is executed correctly within an AJAX request a few lines below, will show you the code:
This instruction is giving me the problem:
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
And this, the function I want to run with the "onclick"
function agregar_pensum_etapa2(td,subject,level,stage){
$(document).ready(function(){
// Capture variables.
var id_periodo = $("#id_periodo").val();
var id_asignatura = subject;
var id_nivel = level;
var id_etapa = stage;
var id_mencion = null;
if (level> 3) {
id_mencion = 0;
}
// Modifiable column.
var tr = $(td).parent();
var index_td = $(td).index();
// First field
var valor_anterior = $(td).text();
$(td).html("<img src =" images / save_64.png 'width = '16' height = '16 '> & nbsp; & nbsp; & nbsp;' + '<input value = "' + valor_anterior + '" type = "text" style = "width: 40px; border: 1px solid #aaa;" onkeypress = "return soloNumeros (event);" maxlength = "2"> ');
$(td).removeAttr("onclick");
$(td).find("input").focus();
// Second field
var valor_anterior_cs = $(tr).find("td:eq("+(index_td+1)+")").text();
var checked_cs = "";
if (valor_anterior_cs === "X"){checked_cs = "checked"}
$ (tr) .find ("td: eq (" + (index_td + 1) + ")") html ("<input type = 'checkbox'" + checked_cs + ">").
// Third field
var valor_anterior_hum = $(tr).find("td:eq("+(index_td+2)+")").text();
var checked_hum = "";
if(valor_anterior_hum === "X") {checked_hum = "checked"}
$(tr).find("td:eq("+(index_td+2)+")").html("<input type = 'checkbox'"+checked_hum+">");
/ ************************************************* *********** /
$(td).find("img").click(function(){
var hora_asignatura = $(td).find("input").val();
var mencion_cs = "NO";
if($(tr).find("td:eq("+(index_td+1)+")").find("input").is ("checked")){mencion_cs = "YES";}
var mencion_hum = "NO";
if($(tr).find("td:eq("+(index_td+2)+")").find("input").is("checked")){mencion_hum = "YES";}
if(hora_asignatura === ""){
if(valor_anterior != ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+index_td+1)+")").text(valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text(valor_anterior_hum);
}else{
$(td).html("");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject +"','"+level+"','"+stage+"');");
}else if(hora_asignatura == "0"){
if(valor_anterior! = ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+(index_td+1)+")").text (valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text (valor_anterior_hum);
}else{
$(td).html("<img src =" images / diagonal.png 'height = '16' style = 'width: 15px ">");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject+"','"+level+ "','"+stage+"');");
}else{
$.ajax({
async: true,
cache: false,
dataType: "html"
type: 'POST'
url: "../Controlador/CtrlPensum.php"
data: {
id_periodo: id_periodo,
id_asignatura: id_asignatura,
id_nivel: id_nivel,
id_etapa: id_etapa,
hora_asignatura: hora_asignatura,
mencion_cs: mencion_cs,
mencion_hum: mencion_hum,
id_mencion: id_mencion,
record: "register"
},
success: function (response) {
//alert (response);
if($.trim(answer) === "1") {
$(td).html(hora_asignatura);
var marcar_cs_x = "";
if(mencion_cs === "SI"){marcar_cs_x = "X";}
var marcar_hum_x = "";
if(mencion_hum === "SI"){marcar_hum_x = "X";}
$(tr).find("td:eq("+(index_td+1)+")").html (marcar_cs_x).
$(tr).find("td:eq("+(index_td+2)+")").html (marcar_hum_x).
\\// --> HERE IT WORKS <-- \\//
$(td).attr("onclick", "agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
cargarTablaResumen ();
} Else {
alert ("Error SQL statement is not executed." + response);
}
//tr.fadeOut(500).fadeIn(500);
},
beforeSend: function () {}
Error: function (objXMLHttpRequest) {}
});
}
});
});
}
I try this:
$(td).click(function(){
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+ "','"+stage+"');");
});
And in the html it prints correctly but does not work, like he was not the "onclick" there. And the function if it works, I put the onclick to that function when I load the page and if it works, but when I click the td and give back to click to restore does not restore the onclick.
Instead of setting the onclick attribute, why not do use .click() again with closures? So your code would be something like...
$(td).click(function(){
var td = this;
$(td).click(function () {
agregar_pensum_etapa2(td,subject,level,stage);
});
});
Do you write
$(Document)
Instead of $(document) with small letter "d".
I don't have all that much experience with Prototype and I've been working with jQuery to get things working properly on our site found here. Today I've added a jQuery based script for session handling. The problem I'm having is that even though I've gotten so far today in terms of functionality, I can't seem to get the change event fired via jQuery.
I'm using the following code currently, but it isn't working properly (you can test it on the site.. as soon as you change the year using your mouse, the AJAX is triggered and a Make can be selected)...
var yearSelected = jQuery.jStorage.get("yearSelected");
console.log(yearSelected);
// Set the vars...
if ((jQuery("div.amfinder-horizontal td:nth-child(1) select").val() == "0")) {
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
jQuery("div.amfinder-horizontal td:nth-child(1) select").trigger('change');
console.log('Set the year!');
}
The following code is the Prototype script controlling this and I need to fire off the change event, and would love to do it via jQuery if at all possible.
var amFinder = new Class.create();
amFinder.prototype = {
initialize: function(containerId, ajaxUrl, loadingText, isNeedLast, autoSubmit)
{
this.containerId = containerId;
this.ajaxUrl = ajaxUrl;
this.autoSubmit = Number(autoSubmit);
this.loadingText = loadingText;
this.isNeedLast = Number(isNeedLast);
this.selects = new Array();
//possible bug if select order in the HTML will be different
$$('#' + this.containerId + ' select').each(function(select){
select.observe('change', this.onChange.bindAsEventListener(this));
this.selects[this.selects.length] = select;
}.bind(this));
},
onChange: function(event)
{
var select = Event.element(event);
var parentId = select.value;
var dropdownId = 0;
/* should load next element's options only if current is not the last one */
for (var i = 0; i < this.selects.length; i++){
if (this.selects[i].id == select.id && i != this.selects.length-1){
var selectToReload = this.selects[i + 1];
if (selectToReload){
dropdownId = selectToReload.id.substr(selectToReload.id.search('--') + 2);
}
break;
}
}
this.clearAllBelow(select);
if (0 != parentId && dropdownId){
var postData = 'dropdown_id=' + dropdownId + '&parent_id=' + parentId;
new Ajax.Request(this.ajaxUrl, {
method: 'post',
postBody : postData,
evalJSON : 'force',
onLoading: function(){
this.showLoading(selectToReload);
}.bind(this),
onSuccess: function(transport) {
if (transport.responseJSON){
this.clearSelectOptions(selectToReload);
var itemsFound = false;
transport.responseJSON.each(function(item){
itemsFound = true;
var option = document.createElement('option');
option.value = item.value;
option.text = item.label;
option.label = item.label;
$(selectToReload).appendChild(option);
});
if (itemsFound){
$(selectToReload).disabled = false;
}
}
}.bind(this)
});
}
},
isLast: function(select)
{
return (this.selects[this.selects.length-1].id == select.id);
},
isFirst: function(select)
{
return (this.selects[0].id == select.id);
},
clearSelectOptions: function(select)
{
$(select).descendants().each(function(option){
option.remove();
});
},
clearAllBelow: function(select)
{
var startClearing = false;
for (var i = 0; i < this.selects.length; i++){
if (startClearing){
this.clearSelectOptions(this.selects[i]);
$(this.selects[i]).disabled = true;
}
if (this.selects[i].id == select.id){
startClearing = true;
}
}
var type = (((this.isLast(select) && !this.isNeedLast) && select.value > 0) || ((this.isNeedLast) && ((select.value > 0) || (!this.isFirst(select))))) ? 'block' : 'none';
if ('block' == type && this.autoSubmit && this.isLast(select))
{
$$('#' + this.containerId + ' .amfinder-buttons button')[0].form.submit();
} else {
$$('#' + this.containerId + ' .amfinder-buttons')[0].style.display = type;
}
},
showLoading: function(selectToReload)
{
var option = document.createElement('option');
option.value = 0;
option.text = this.loadingText;
option.label = this.loadingText;
$(selectToReload).appendChild(option);
},
};
I had the same problem. Here is solution. When you create : amfinder-horizontal the html goes something like this
<div class="amfinder-horizontal" id="amfinder_5333ffb212b09Container">
...
</div>
Look at id element : amfinder_5333ffb212b09 Container, bold part is also the name of variable that is amfinder object (created from prototype). It's a random name. This is from the extension source :
<?php $finderId = 'amfinder_' . uniqid(); ?>
...
<script type="text/javascript">
var <?php echo $finderId ?> = new amFinder(
'<?php echo $finderId ?>Container',
'<?php echo $this->getAjaxUrl() ?>',
'<?php echo $this->__('Loading...')?>',
'<?php echo Mage::getStoreConfig('amfinder/general/partial_search')?>',
<?php echo intval(Mage::getStoreConfig('amfinder/general/auto_submit')) ?>
);
</script>
So on every page refresh there is different name. var <?php echo $finderId ?>
Steps :
// Find the name for amfinder object.
var objName = jQuery("div.amfinder-horizontal").attr('id').replace('Container','');
// set Value to that select - copied from your code
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
// call the change event of that object
var targetObj = {
target : jQuery("div.amfinder-horizontal td:nth-child(1) select")[0]
};
window[objName].onChange(targetObj);
I have an arraylist of values which must be passed from one html (javascript) to another.
My code is :
function show_confirm()
{
//var r=confirm("Do you wish to use the existing Details?");
apprise('Do you wish to use the existing details?', {'verify':true}, function(r)
{
if(r)
{
// user clicked 'Yes'
alert("yes");
var a=camera.getDetails();
//window.locaton="http://www.google.co.in/";
var s=a.get(0);
alert(s);
//alert("rettttttttt" + a);
window.location="my_details.html?" + s;
//document.getElementById("location").value=a.get(0) + " ";
//alert(a.get(0) + " ");
//fetch my details from native
}
else
{
// user clicked 'No'
// display new form
alert("no");
}
});
}
</script>
and in my_details.html :
function submitForm(){
//var policyNumber=document.getElementById("number").value;
//var a=camera.getDetails();
var q=window.location.search;
if (q.substring(0, 1) == '?') {
q = query.substring(1);
}
alert("qqqqqqqqqq "+ q);
</script>
How to pass data between scripts?
I resolved it in the following way:
var c=new Array(a); (eg: a={"1","2"})
window.location="my_details.html?"+ c + "_";
and in my_details.html :
var q=window.location.search;
alert("qqqqqqqqqqqqq " + q);
var arrayList = (q)? q.substring(1).split("_"):[];
var list=new Array(arrayList);
alert("dataaaaaaaaaaaa " + list + "llll " );
and in "list" its dusplaying me "1%202";
How can i remove this %20 =space value ??
thanks
Sneha
You mean this?
function show_confirm() {
//var r=confirm("Do you wish to use the existing Details?");
apprise('Do you wish to use the existing details?', {'verify':true}, function(r) {
if(r) {
// user clicked 'Yes'
var a=camera.getDetails();
window.location="my_details.html?" + a.join("_");
}
else {
alert("no");
}
});
}
function submitForm(){
var q=window.location.search;
var arrayList = (q)? q.substring(1).split("_"):[];
}