I have a function for updating multiple selects based on values of another select.
How can I edit this function to use it without prototype just with jquery ?
function replace(val) {
if (val != 0) {
$$('select.replace).each(function(e) {
var aa = e.value.split("_");
if (aa[0] = val) {
e.value = val + "_" + aa[1] + "_" + aa[2];
jQuery("select.replace").trigger("chosen:updated");
}
});
} else {
alert('Please select a valid value');
return false;
}
}
It's simple:
jQuery( 'select.replace' ).each(function() {
var aa = $( this ).val().split("_");
if (aa[0] = val) {
$( this ).val( val + "_" + aa[1] + "_" + aa[2] );
//...
Red more about jQuery val() method.
Try using .change() when the select value is changed.
$( ".target" ).change(function() {
// code here
});
Related
I am having a dropdown when I click on the item in dropdown my list box gets populated with set of items realted to that item selected from dropdown..now when I choose one item from list box I want to fetch its ID..My all data is coming form json..pLEASE HELP!!
$(document).ready(function() {
$.ajax({
url: "DATA.JSON",
dataType: "json",
success: function(obj) {
console.log("obj--", obj)
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled',
location: 'fixed'
}).appendTo('#dropdown1')
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
});
$('#dropdown1').change(function() {
$('#listbox').toggle(this.value != "");
});
$('#dropdown1').change(function() {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
console.log("as".selection);
$.each(jsObject, function(index, value) {
if (value['name'] == selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$("#listbox").css("width", "500px")
$("#listbox").css("height", "300px")
$('#listbox').append(optionHtml);
return false;
}
var selectedOption = $(this).find('option:selected');
console.log(selectedOption);
});
});
$("#listbox").on("click", function() {
console.log("asd", $('#listbox').attr('data-val'));
$( "#listbox" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
})
}
});
});
Change this line of code
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
To
optionHtml += '<option value="' + attr + '" id="'+ attr+'">' + value[attr] + '</option>';
Change this code block
$("#listbox").on("click", function() {
console.log("asd", $('#listbox').attr('data-val'));
$( "#listbox" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
});
TO
$( "#listbox" ).on( "click", "option", function() {
$( this ).toggleClass( "chosen" );
alert($(this).attr('id')); // this is just for demo to get the id of the clicked option.
});
Points to note.
1) your #listbox does not have a td element at all. All it has is <option> tags. So change the script to trigger the click event on this option.
2) You are binding the click event to your td (which mut be option) on every click of the #listbox which will cause you binding multiple events and that will cause failure.
3) use the .on() selector over .delegate. .delegate() is deprecated and as of now it doesnt work in most of the mobile browsers.
Parameters you are passing is not in order:
.delegate( "td", "click", function() {
You should first assign the click event and then the selector:
$( "#listbox" ).delegate( "click", "td", function() {
$( this ).toggleClass( "chosen" );
});
And you should also use e.stopImmediatePropagation inside listbox click function.
Suggestion: You should use on method instead of delegate method.
Im working in a chat system very simple. But i have a problem. I can only get the other user messages if i close and re open the chat conversation div, then the message appears.
How can I solve this? The problem should be in this piece of code. As I am not very comfortable with ajax I ask for your help.
JS:
$(document).ready(function(){
var snd = new Audio("images/new_msg.wav");
var open=Array();
$("#jd-chat .jd-online_user").click(function(){
var user_name = $.trim($(this).text());
var id = $.trim($(this).attr("id"));
if($.inArray(id,open) !== -1 )
return
open.push(id);
$("#jd-chat").prepend('<div class="jd-user">\
<div class="jd-header" id="' + id + '">' + user_name + '<span class="close-this"> X </span></div>\
<div class="jd-body"></div>\
<div class="jd-footer"><input id="textareabox" placeholder="escrever..."></div>\
</div>');
$.ajax({
url:'chat.class.php',
type:'POST',
data:'get_all_msg=true&user=' + id ,
success:function(data){
$("#jd-chat").find(".jd-user:first .jd-body").append("<span style='display:block' class='me'> " + data + "</span>");
}
});
});
$("#jd-chat").delegate(".close-this","click",function(){
removeItem = $(this).parents(".jd-header").attr("id");
$(this).parents(".jd-user").remove();
open = $.grep(open, function(value) {
return value != removeItem;
});
});
$("#jd-chat").delegate(".jd-header","click",function(){
var box=$(this).parents(".jd-user,.jd-online");
$(box).find(".jd-body,.jd-footer").slideToggle();
});
$("#search_chat").keyup(function(){
var val = $.trim($(this).val());
$(".jd-online .jd-body").find("span").each(function(){
if ($(this).text().search(new RegExp(val, "i")) < 0 )
{
$(this).fadeOut();
}
else
{
$(this).show();
}
});
});
$("#jd-chat").delegate(".jd-user input","keyup",function(e){
if(e.keyCode == 13 )
{
var $cont = $('.jd-body');
var box=$(this).parents(".jd-user");
var msg=$(box).find("input").val();
var to = $.trim($(box).find(".jd-header").attr("id"));
$.ajax({
url:'chat.class.php',
type:'POST',
data:'send=true&to=' + to + '&msg=' + msg,
success:function(data){
$('#textareabox').val('');
$(box).find(".jd-body").append("<span style='display:block' class='me'> " + msg + "</span>");
$cont[0].scrollTop = $cont[0].scrollHeight;
$cont.append('<span>' + $(this).val() + '</span>');
$cont[0].scrollTop = $cont[0].scrollHeight;
$(this).val('');
}
});
}
});
function message_cycle()
{
$.ajax({
url:'chat.class.php',
type:'POST',
data:'unread=true',
dataType:'JSON',
success:function(data){
$.each(data , function( index, obj ) {
var user = index;
var box = $("#jd-chat").find("div#2").parents(".jd-user");
$(".jd-online").find(".light").hide();
$.each(obj, function( key, value ) {
if($.inArray(user,open) !== -1 )
$(box).find(".jd-body").append("<span style='display:block' class='other'> " + value + "</span>");
else
snd.play();
$(".jd-online").find("span#" + user + " .light").show();
});
});
}
});
}
setInterval(message_cycle,1000);
});
How messages are displayed when you first open the chat conv div ?
I'm assuming message_cycle() is supposed to display new messages in your div every second, i suppose your problem is here...
I'm not really confortable with this :
var box = $("#jd-chat").find("div#2").parents(".jd-user");
A div can't have an id starting with a number, you need <div id="chat2"> instead of <div id="2">.
After your line add a console.log('Box found : '+box.length) ; just to make sure your box is correctly found in message_cycle.
I have the following condition in a long function:
if ( shipSet == true ) {
$("#" + shippingFields[i]).style.background = 'gray';
$("#" + shippingFields[i]).className = 'optional';
} else {
$("#" + shippingFields[i]).removeAttribute('style');
$("#" + shippingFields[i]).removeClass('optional');
}
the style lines work fine, whether true or false, but the className and removeClass lines aren't working. Any suggestions? Am I just not using them properly?
Since ("#" + shippingFields[i]) return a jQuery object.
You need to use addClass() and removeClass() instead:
if ( shipSet == true ) {
$("#" + shippingFields[i]).css('background','gray');
$("#" + shippingFields[i]).addClass('optional');
} else {
$("#" + shippingFields[i]).removeAttr('style');
$("#" + shippingFields[i]).removeClass('optional');
}
Also, you can use css() to set the styles of your elements.
You should use addClass (to add class to element) and removeClass (to remove class from element):
$("#" + shippingFields[i]).addClass('optional');
$("#" + shippingFields[i]).removeClass('optional');
if ( shipSet == true ) {
$("#" + shippingFields[i]).css('background','gray');
$("#" + shippingFields[i]).addClass('optional');
} else {
$("#" + shippingFields[i]).removeAttr('style');
$("#" + shippingFields[i]).removeClass('optional');
}
Try this, for adding class name use always $("#attributeID").addClass('ClassName');
if ( shipSet == true ) {
$("#" + shippingFields[i]).css('background','gray');
$("#" + shippingFields[i]).addClass('optional');
} else {
$("#" + shippingFields[i]).removeAttr('style');
$("#" + shippingFields[i]).removeClass('optional');
}
I want to do a search by name and surname with an array javascript, and the results in a div. for example: I write Ali in input, an it shoul show me Alison and Alibaba.
this is my code, but it's giving errors; are there other ways to do it?:
<input type='text' id='filter' placeholder='search'>
<div id='output' style='margin-top:50px '></div>
my array
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#output');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
console.log( item[0].toLowerCase().indexOf(val));
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item[0] + ' ' + item[1] + '</li>');
}
});
$result.html( $fragment.children() );
});
http://jsfiddle.net/henrykend/ChpgZ/4/
The main problem with your code is that you're trying to reference fields in the object by ordinal position rather than name. There is nothing automagic in JavaScript which will read item.Name (or item["Name"]) from item[0].
There is also no need to build up a "false element" (in your case $fragment) and then append its children to the output area - you may as well do this in one go (remembering to .empty() it between calls).
Your corrected code:
var $result = $('#result');
$('#output').on('keyup', function () {
$result.empty();
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$result.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
});
And a live example: http://jsfiddle.net/ChpgZ/6/
You had couple of problems in your code.
Names of the elements we're wrongly placed (which you've fixed with the edit)
In the .each, you've used item[0] instead of item.Name (also surname)
See the following code
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#result');
$('#output').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {console.log( item.Name.toLowerCase().indexOf(val) );
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
$result.html( $fragment.children() );
});
var settings = {};
$(".js-gen-settings").each(function(){
var date;
if (($(this).attr("type") === "checkbox") || ($(this).attr("type") === "radio")){//if its a checkbox
eval("settings."+this.name+" = "+$(this).is(":checked"));
}else{
date = $(this).val();
if (date == ""){
eval("settings." + this.name + " = null");
}else{
eval("settings." + this.name + " = '" + date + "'");
}
}
});
a JSON.stringify version of settings will be sent to the server using ajax.
If you want to modify a property of an object dynamically, you just put the name in [brackets].
settings[this.name] = null
settings[this.name] = date;
settings[this.name] = $(this).is(":checked");
change:
eval("settings." + this.name + " = null")
to
settings[this.name] = null;
I'm sure you can figure out the rest :)
Here, I've re-factored your code:
$( '.js-gen-settings' ).each(function () {
if ( $( this ).is( ':checkbox, :radio' ) ) {
settings[ this.name ] = this.checked;
} else {
settings[ this.name ] = this.value ? this.value : null;
}
});