I am attempting to:
Use JQuery to 'loop' through all elements on a page that belong to the same CSS class ("boilerplate")
Check the current value of each against it's server side assigned value (property: StaticPrefill)
Apply a special css class ("editedbackcolor") if the two values do not match (ie I'm trying to flag when someone has edited the prefilled text on textboxes)
CSS I am using:
.boilerplate = assign to all text boxes I'm trying to check on the form
.editedbackcolor = different shade I want to assign to textboxes where current value does NOT equal server side StaticPrefill value.
jQuery code I have so far is:
jQuery(document).ready(function () {
// select each element with class boilerplate and run a function against it
jQuery('.boilerplate input').each(function () {
var target1 = jQuery(this).attr("id");
matchcheck(target1);
});
});
and I'm working on the "matchcheck) function which is where I am having a problem. I'm trying to pull back the server side "StaticPrefill" property value that I can use as a comparison. I've successfully queried this by hardcoding a control name, like:
function matchcheck(){
var TSP1 = '<%= TextBox1.StaticPrefill %>';
// If current textbox value does NOT equal it's static prefill value
if (document.getElementById("Textbox1_textbox1").value != TSP1) {
alert("TB1 has differnt value than static prefill");
// change background color to flag it
jQuery("#Textbox1_textbox1").addClass("EditedBackColor");
}
}
That works fine, but I don't want to use a variable to loop through all elements instead of the hardcoded "TextBox1" in the first line of the function. I've tried different syntaxes in an attempt to put a variable between the '<%= ' and '%>' tags but the page won't compile when I try this.
Is this possible w/o using code behind of some sort? Any suggestions?
An easier approach, if I understand your question, is to bind to the change event in jQuery.
$(document).ready(function() {
jQuery('.boilerplate input').change(function() {
if(jQuery(this).val() !== jQuery(this).attr("prefill")) {
jQuery(this)removeClass('boilerplate').addClass("EditedBackColor");
}
});
});
You will also need to add an attribute called "prefill" to your input elements. You can do that server side or client side. It should look something like this:
<input class="boilerplate" id="input1" type="text" prefill="123" value="123"/>
The caveat here is that if they change it back to the original value, it will still show as changed. I'm not sure if that works for you in your scenario. They did change it per se. You would have to save off the original value as an attribute if it did not exist. The other option is to send down a model, maybe a json object, and compare to that model based on index.
Related
I have the following div (this was already given to me, I did not create it):
<div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1500, "pause": 5000}'>
as far as my understanding goes (please correct me if I am wrong), we are saying here, that I want to assing the following values (such as slideCount, moveCount, customLink, etc...) to the object named data-sudo-slider.
What I am trying to do in my underlying JavaScript, is to retrieve the value of pause from this object. Here is what I am doing:
var sudoEl = jQuery('[data-sudo-slider]');
var pause = sudoEl.pause;
Even though it recognized the slider object, it did not retrieve the value for pause I have passed in (returned value is undefined.
How can I retrieve this value?
You can use data() like this:
The .data() method allows us to attach data of any type to DOM
elements in a way that is safe from circular references and therefore
from memory leaks. We can retrieve several distinct values for a
single element one at a time, or as a set:
$('[data-sudo-slider]').data('sudoSlider').pause;
why did you have to specify 'sudoSlider'?
You can also use sudo-slider.
It worked as the property name is derived as following:
The attribute name is converted to all lowercase letters.
The data- prefix is stripped from the attribute name.
Any hyphen characters are also removed from the attribute name.
The remaining characters are converted to CamelCase. The characters immediately following the hyphens removed in Step 3 become uppercase.
You can get this property by:
$(function () {
var pause = $('[data-sudo-slider]').data('sudoSlider').pause;
});
$('[data-sudo-slider]') is the div element, where data-sudo-slider is defined. .data('sudoSlider') is the data property value. data is working with - signs a littlebit different, you can read about it in jQuery data documentation.
.pause is the property of JSON object.
You should use .data() to fetch data-sudo-slider value.
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
var sudoEl = jQuery('[data-sudo-slider]').data('sudo-slider');
alert(sudoEl.pause);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1500, "pause": 5000}'>
To retrieve the correct element use
var element = $("div[data-sudo-slider]");
You can either get the data-sudo-slider attribute via
var sudoSlider = element.attr("data-sudo-slider");
In which case you will have to convert the string to JSON to access the pause property:
var pause = JSON.parse(sudoSlider).pause;
or better yet, use the .data() method
var sudoSlider = element.data("sudoSlider");
var pause = sudoSlider.pause;
When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);
Sorry for bad wording in the question but it's hard to explain for me. I'm using several bxsliders on a page and some are placed in hidden divs. Unfortunately images are not shown in the slider after making the parent div visible unless the slider is reloaded (See here: bxSlider within show/hide divs). So let's say I initiate the sliders at the beginning with:
var slider_0=$("#slider_0 .bxslider").bxSlider({
//bxslider options here
});
var slider_4=$("#slider_4 .bxslider").bxSlider({
//bxslider options here
});
var slider_7=$("#slider_7 .bxslider").bxSlider({
//bxslider options here
});
The sliders are not consecutively numbered but there is a navigation and if I click the 7th element it leads to slider_7. So I could get the index of the clicked item with:
$(this).index();
When I call slider_7.reloadSlider(); it would work but I don't know which slider the user clicks and which number it has. So would it be possible to call that with a created string like this:
slider_name='slider_'+$(this).index();
slider_name.reloadSlider();
works not of course. Is there a way to do it?
I would create a dictionary with strings as keys and functions as values. Then, you could have O(1) lookup of the functions you're targeting.
In general, you can do it like so:
// set up your dictionary
var dictionary = {};
// add your functions
dictionary['methodName'] = function() {};
// call the functions
dictionary['methodName']();
So, for your example, you could do:
dictionary['slider_7'] = slider_7.reloadSlider;
dictionary['slider_'+$(this).index()]();
You could trigger it with
window["slider_" + $(this).index()].reloadSlider()
Although, I'm not sure whether your approach is the best. I think I'd go with arrays or with object (as a key-value pairs)
Try this:
slider_name='slider_'+$(this).index();
$("#" + slider_name + " .bx_slider").reloadSlider();
Found a working solution:
eval("slider_" + $(this).index()).reloadSlider();
Its not entirely clear here what you want/are trying to do. What it seems like you want to do is get a programmatic handle on a specific slider when a user clicks a specific part of your page. You do not accomplish this by eval()ing a string...that's what event handlers are for. So create a click event handler and in that event handler
$('#idOfWhatTheUserClicksOn').click(function(event) {
var slider = document.getElementById('#idOfRelatedSlider');
$(slider).bxSlider();
//if you need the current value of the slider you can get that too
var value = slider.value;
});
You could achieve the same with fewer LOC by using a class instead of id's with different handlers, but the concept is the same.
var slider_cache = [
$("#slider_0 .bxslider").bxSlider(),
$("#slider_1 .bxslider").bxSlider(),
$("#slider_2 .bxslider").bxSlider()
];
...
slider_cache[$(this).index()].reloadSlider();
I'm successfully creating some dynamic input textboxes using the following javascript:
var type = "Textbox";
var foo = document.getElementById("fooBar");
for (i = 1; i <= totalQty; i = i + 1) {
var textbox = document.createElement("input");
//Assign different attributes to the element.
textbox.setAttribute("type", type + i);
//textbox.setAttribute("value", type + i);
textbox.setAttribute("name", type + i);
textbox.setAttribute("id", type + i);
textbox.setAttribute("style", "width:300px");
textbox.setAttribute("width", "300px");
//Append the element in page (in span).
var newline = document.createElement("br");
foo.appendChild(newline);
foo.appendChild(textbox);
}
Everything works fine with that. Once the user keys in data and clicks submit however, I need to go back and set the background-color of any textboxes with an error to red. I found some code to do the actual coloring:
textbox.style.backgroundColor = "#fa6767";
...and I know the exact name of the textbox with the error (i.e. "Textbox1", "Textbox2", "Textbox3", etc) but I'm not sure how to programatically assign this background color code to the specific textbox. I can't use something like this, since all code is dynamically generated:
errorTextbox = $("#Textbox1");
Any suggestions?
It looks like you're building a form validation script. Here's an easier way to do this:
1) Create an entry in your stlyesheet for your error class. Adding and removing a class requires fewer steps than assigning properties individually.
.error {
background-color: #ff0000;
}
2) Give all the textboxes you wish to validate a unique class name "valMe", for example.
3) Then loop through them during the validation step:
$('.valMe').each(function() {
$(this).removeClass('error');
if($(this).text=='') {
$(this).addClass('error');
}
})
By using "this" you refer to the current element, so you don't even need to know the ID of the element.
If you already know the name (in this case identical to the id) of the element, you can use jQuery to select the element by forming the selector using string concatenation. Assuming you have a variable that stores the name/id of the text box that has the error, then it's a relatively simple process:
var errorTextboxName = 'Textbox1';
$('#' + errorTextboxName).css('background-color', 'red');
I ended up going with the following:
document.getElementById('Textbox1'.style.backgroundColor = "#fa6767";
I originally didn't think I would be able to capture my "Textbox1" control in this fashion since when I viewed the html source code, there was no "Textbox1" due to the fact I dynamically created it.
Thanks.
The problem is simple. I have something like chessboard in HTML. The fields have coordinates, stored in ID attribute (ROW|COLUMN)
Clicking on a specific field makes it marked/unmarked. What is more, selected field's row and column are stored in a <input type="hidden"/> in the form of ROW|COLUMN,ROW|COLUMN,...
For every click I have to process the value of input hidden to check whether the field is already stored, add new field, remove existing and so on. It's a little awkward.
Are there any better ways? Or maybe it is the best way?:)
You don't have to store the fields state in an input field. Better use the a global JavaScript array or manipulate the DOM and serialize it's state before sending it to the server.
Here is some sample code in a JSFiddle: http://jsfiddle.net/U2D9Q/
The important part is where the className of the columns
$td.bind("click", function(e) {
$(this).toggleClass("selected");
});
and how it's serialized when you click the button
var serialize_table = function() {
var output = new Array();
$("table tbody").children().each(function(y) {
var row = new Array();
$(this).children().each(function(x) {
row[x] = $(this).get(0).className;
});
output[y] = row;
});
return output;
}
I used jQuery to keep the code clean. Feel free to use any JS Framework you like or write native JS.