It's a pretty simple trick that I thought should work fine however it doesn't. So I have multiple checkboxes on the page. And whenever they are changed I would like to record any change to the database. So in the view event 'click' on checkbox I have similar to this:
var filter_name = $(e.target).attr("name");
var filter_value = $( "input:checkbox[name=" + filter_name + "]:checked" ).map(function () {
return this.value;
}).get();
console.log("filter_name: " + filter_name); #=> my_method_name
CarInsuranceApp.aciq.set({filter_name: filter_value});
CarInsuranceApp.aciq.save();
And here the results that I receive as a JSON:
"filter_name"=>"extra"
So my question would be how to dynamically pass model attribute name on the set?
use like this.
CarInsuranceApp.aciq.set(filter_name, filter_value);
Here is a possible one line JavaScript`ish solution:
CarInsuranceApp.aciq.attributes[filter_name] = filter_name;
Related
I am new at jQuery/javascript. I tried some suggestions I found on this forum but so far it did not help.
THis is what I am trying:
When loading categories from a database ( using ajax) this HTML statement is added for each category:
$("#Links ul").append('<li id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
Using F12 I see that the lines are correctly added.
E.g. <li id="cat3" data-catid="3">Seafood </li>
Next step is selecting a category in the screen and retrieve the products of this category using the value set for data-catid.
I have been told that I could "this.id" but so far no luck. Displaying the value of this.id with alert returns the correct value but for some reason I can't use it.
When I add (#cat3).attr(“data-catid”) in the code it works. But different options like these did not work:
("#cat"+ this.id).attr(“data-catid”)
(this).attr(“data-catid”)
var x = $(this).id();
var rest = x.substr(4, 1);
Everything with "this" creates error : Uncaught TypeError: ("#cat" + this.id).attr is not a function...
Trying to display any of these options does not give any output (not even a popup when I set an alert)
Any help would be appreciated!
You are loading dynamic values. Please use Event Delegation. And the $.one() binds the event once.
You need to add this in your ready function.
$(document).ready(function () {
$("#Links ul").one("click", ".cat", function(){
alert($(this).data('catid'))
});
});
To get the IDs of the elements, use $(this).attr("id") or $(this).prop("id") (latest jQuery) instead of this.id, as sometimes, it might return the jQuery object.
As you are creating elements like
$("#Links ul").append('<li class="cat" id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
create elements using jQuery
$("#Links ul").append( $('<li></li>', {
class: "cat",
id: "cat" + i,
data-catid: i,
text: categorie_tekst[1]
});
As you are creating elements dynamically use Event Delegation. You have to use .on() using delegated-events approach.
$(document).ready(function () {
$("#Links ul").on(event, ".cat", function(){
alert($(this).data('catid'))
});
});
Pretty sure I know the solution... would write .on('change','load', function(){}
correct? <-- Tested didn't work? so I am up to your solutions :)
Sushanth -- && adeneo both came up with great solutions, this is a good lesson in optimizing code... It's gonna be hard to choose which answer to go with, but I know this is going to help me rethink how I write... I dont know what I do without this forum, id have to learn this stuff in college.
This is purely a question out of curiosity and bettering my skills, as well as giving you guys a chance to display your knowledge on jQuery. Also to prevent any sloppy writing.
I have a radio based switch box, the markup looks like this, the id's and on/off values are generated by the values in my array with PHP...
<span class="toggle-bg">//This color is the background of the toggle, I need jQuery to change this color based on the state on/off
<input type="radio" value="on" id="_moon_page_header_area1" name="_moon_page_header_area">//this is my on value generated by the array
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">// I create this input because I have multiple checkboxes that have the ID _moon_ARRAYVALUE_area1
<input type="radio" value="off" id="_moon_page_header_area2" name="_moon_page_header_area">// off value
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">//_moon_ARRAYVALUE_area2
<span class="switch"></span>// the switch button that changes
</span>
Hope that makes sense and the comments are clear
Here is the jQuery
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.hide()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.show()
}
$('.toggle-bg').change(function () {
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.slideUp()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.slideDown()
}
});
it looks longer than it really is, its just repeating it self, one is on load so that it gives the correct color on load of the page, and then inside the change function we need to change colors..
How do I write it so I only have to use variables one time (so its cleaner) is there a better way to optimize it... Just NOW thinking after writing this I could put it in one function .on('load', 'change', function() {}
I just now thought of that, but I wrote all this so I am going to see what others think...
You'd do that by having the function in the change event handler, and on the end you chain on a trigger('change') to make it work on pageload :
$('.toggle-bg').on('change', function () {
var value = $('.toggle-bg input.switch-id-value').val(),
moon1 = $('#' + value + '1').is(':checked'),
slider = $('._moon_staticarea_height'),
toggle = $('.toggle-bg');
toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
slider[moon1?'slideUp':'slideDown']();
}).trigger('change');
As radiobuttons can't be unchecked, it's either moon1 or moon2, which means checking one of them should be enough.
.on('change','load',
supposed to be
// Remove the comma separator if you want to bind the same handler to
// multiple events.
.on('change load',
And you can remove the one separately written out and enclose it in a function (if multiple instances of the class toggle-bg)
or just trigger the change event.(If there is a single instance of a class)
This will just run the same functionality when the page loads.
var toggle = $('.toggle-bg');
toggle.change(function () {
var value = $('input.switch-id-value', this).val(),
moon1 = $('#' + value + '1').is(':checked'),
moon2 = $('#' + value + '2').is(':checked'),
static_slide = $('._moon_staticarea_height');
if (moon1) {
toggle.css({
'background-color': '#46b692'
});
static_slide.slideUp()
} else if (moon2) {
toggle.css({
'background-color': '#333'
});
static_slide.slideDown()
}
}).change();
I have a form which contains hundreds of checkboxes, I need to make some of them to be checked.
I am getting checked value from server.
To filter them out and make them checked I do the following:
JavaScript/jQuery
var userChangeProcess = function(object){
console.log("userChangeProcess called", object);//1 object i am getting
$.each(object, function(key,value){
if(value.hasOwnProperty("Add")){
console.log(value["Add"]);//i am getting 4 names of value
var userLocales = $(':checkbox',"form").filter(function(){
return $(this).val() === value["Add"] ? $(this).prop("checked",true).parent().addClass("green") : "";
});
}
})
I also tried doing it this way (without success):
$(":checkbox[value='"+value["Add"]+"']","form").parent().addClass("green");
It's not working. what is wrong in my function?
What are you trying to accomplish by setting the var userLocales? If you're just trying to check a box and add a class, you could use some form of the following:
$('input[type="checkbox"]', "form").filter(function(){
return $(this).val() === value["Add"]
}).prop("checked",true).parent().addClass("green")
I have 2 dropdownlists on a asp page.
If user changes the selected index of the first drop down list, then set DDL2.selectedindex = DDL1.Selectedindex
and do this same logic except switch DDL1 and DDL2 respectively. I have these both getting populated from the same list of objects(just different properties set to each) and i have a order by clause on the query to ensure the data stays in sync. My question is how can i get this logic to work in javascript? My current method is as such..
Accounts.Attributes.Add("onBlur", Customers.SelectedIndex = Accounts.SelectedIndex)
Customers.Attributes.Add("onBlur", Accounts.SelectedIndex = Customers.SelectedIndex)
This code doesn't work but demonstrates what im shooting for. When the ddl getting the first selection loses focus, populate the other ddl(setting the selected index). Any help would be great!
Can someone see what i'm doing wrong here?
$("[id$=ddlStandardAcctNo]").change(function () {
var acc = $("[id$=ddlStandardAcctNo]");
var cust = $("[id$=ddlCustomerName]");
cust.selectedindex = acc.selectedindex;
});
It compiles and just doesn't work... :( These drop downs are inside of a asp gridview.
After looking at that i'm trying to do this..
$("[id$=ddlStandardAcctNo]").blur(function () {
var acc = document.getElementById('<%=ddlStandardAcctNo.ClientID %>');
var cust = document.getElementById('<%=ddlCustomerName.ClientID %>');
cust.selectedindex = acc.selectedindex
});
$("[id$=ddlCustomerName]").blur(function () {
var acc = document.getElementById('<%=ddlStandardAcctNo.ClientID %>');
var cust = document.getElementById('<%=ddlCustomerName.ClientID %>');
acc.selectedindex = cust.selectedindex
});
Problem is i never use document.ready cause the dropdownlist are in a gridview. I'm literally just learning javascript/jquery as i run across issues like this so feel free to crack the knowledge whip lol.
I figured this out finally!!!! the solution for jquery prior is the following
$("[id$=ddlStandardAcctNo]").change(function () {
$("[id$=ddlCustomerName]").attr("selectedIndex", this.selectedIndex);
});
$("[id$=ddlCustomerName]").change(function () {
$("[id$=ddlStandardAcctNo]").attr("selectedIndex", this.selectedIndex);
});
This example is simplified a bit, but in my ASP.NET web page in my c#/jquery code I am using a right hand context menu that displays ‘rightMenu’ when a right mouse is clicked.
$(document).ready(function() {
$(".RH_signoffrow td").contextMenu({
menu: 'rightMenu'
},
function(action, el, pos) {
var mykey = getkeyforitem(el);
mykey = "Details|" + mykey;
alert(
'Action: ' + action + '\n\n' +
'Key is: ' + mykey
);
if(action == "details"){
trigger_details_panel(mykey);
}
});
};
//for any td in the right hand side - get its row key
function getkeyforitem(el){
var mykey = $(el).parent().find('.hiddenrowkey').text();
// alert(
// 'Internal getkeyforitem Call' + '\n\n' +
// 'Key is: ' + mykey
// );
return mykey;
};
The callback of the menu passes back the element that was clicked, and that can be used to pull the keydata out of the current table row. Once I have that keydata, I can use it to call the real function I was after:
trigger_details_panel(mykey).
This works fine if I only want to use the right mouse, but I want to include an image in some of the rows, so that when the image is clicked, it produces the same effect,as the right mouse menu selection.
I am not sure how to accomplish that cleanly.
I can include an image that links to javascript in my page…
<asp:ImageButton ID="imgDetails" runat="server" ToolTip="Show Details"
ImageUrl="./images/details.gif" OnClientClick="showdetailsclicked();return
false;"></asp:ImageButton>
But how can I get it to call the code:
getkeyforitem(el);
Or at least know the element (el) it belongs to? It seems like there should be a way to use the (this) pointer to get at what I want - but I don't see it.
Am I just missing a more straightforward way to accomplish the whole problem?
If you replace the line:
var mykey = $(el).parent().find('.hiddenrowkey').text();
with
var mykey = $(el).parents("tr").find('.hiddenrowkey').text();
Then you can use this function to find the hidden rowkey from any element in the row.
Edit after comment:
You were right about using this. I'd probably do something like:
function showdetailsclicked(){ var rowKey = getkeyforitem(this);}
However, Im not sure if theres some issue with ASP, I doubt it, but you never know... You may have to do something like:
<asp:ImageButton ID="imgDetails" runat="server" ToolTip="Show Details"
ImageUrl="./images/details.gif" OnClientClick="showdetailsclicked(this);return
false;"></asp:ImageButton>
function showdetailsclicked(el){ var rowKey = getkeyforitem(el);}
Hope that helps!