overriding data-confirm values - javascript

I want to change the value of data-confirm attribute on a button (submit) based on user's choices on a form. I put the following on the change function of a dropdown list:
...
if($("#"+select_name).val() == "abc")
{
$(".variable_button").attr("data-confirm","abc is good choice!");
} else
{
$(".variable_button").attr("data-confirm","abc would have been great but this is fine too...");
}
...
The problem I am facing is that apparently data-confirm cannot be changed once it is assigned a non-empty string. I have it set to "" in the server code. And, it changes to one of the two messages shown above when the user first makes a selection on the dropdownlist. But if the user changes the selection one more time, the data-confirm message does not change. Is this per design or am I missing something?

Don't use .attr(), use .data():
var newData = ($("#"+select_name).val() == "abc")
? "abc is good choice!"
: "abc would have been great but this is fine too...";
$(".variable_button").data("confirm", newData);

jQuery does allow you to update a data- attribute with the .attr() method, so something else is breaking.
Here's a working example (JSFiddle):
var counter = 1;
$('#click').click(function() {
button = $('#click');
console.log(button.attr('data-confirm'));
button.attr('data-confirm', 'this is test ' + counter);
console.log(button.attr('data-confirm'));
counter++;
});
Can you try to repo the issue in a JSFiddle?
On rereading your question, it sounds like an event handler isn't firing the second time the user changes the selection. See if you can set a breakpoint in your event handler to see if it even gets hit.

Related

Configuration form with a custom control in leaflet

I'm trying to create a custom control using leaflet; here you can see the jsfiddle: https://jsfiddle.net/1tca13f3/
When the user clicks on the submit button, i need to read the value from the dropdown and the one from the text field.
This...
L.DomEvent.on(this._container, 'click', this._doSomething, this);
...as predictable, doesn't work.. and I can't read the values from the input fields. How can I do this?
The main issue you are having is that you are just alerting the string 'clicked' in your _doSomething() function. You need to look up all the values and then you can do what ever you want with those values. Here is some quick code that will at least get you going in the right direction.
_doSomething: function(event){
if(event.target.className === 'leaflet-control-opt-submit') {
var select = document.querySelector('.leaflet-control-opt-dropdown');
var input = document.querySelector('.leaflet-control-opt-input');
console.log(select.value, input.value)
}
}
it first checks to make sure the event.target is the submit button if it is it looks up the values from the inputs and for now we just console.log() them you can do whatever you want from then on with the values.

jQuery selector with variable, not updating when variable changes

'I am trying to do something like the below that will run a function when clicking the "hit" class only when the parent "box" id is correct.
var selected = 1;
$('#box-' + selected + ' .hit').click(function(){
selected = randomFromTo(1,5);
});
The selected variable changes depending on other actions on the page but I can't get the function to work after any change - it stays fixed to the initially selected "box" id. I can imagine why this might be, as jQuery has taken a snapshot of that string and nothing is telling it update it but I can't figure out how to get around this.
Edit: added the selected variable's instantiation and where it gets set. I've left out the UI changes that would make this more understandable to a user.
You could just set the click handler on the .hit class, then check the parent nodes for the right ID within the handler itself. If you do this, make sure you defer the event correctly, otherwise you'll end up with one handler for every single .hit element.
If I understand your problem correctly, the issue is that the selected variable is evaluated at the time your function is created. The function is bound to the click event of a set of DOM elements at that time.
After the binding, it is not possible to modify the selector, and changing any variable used during selection will have no effect.
The best way around this I can think of, is to attach the click event to all possible matches, and then further filter them inside the click handler...
$('.hit').click(function(){
// check if the parent has the correct id
if($(this).parent().attr('id') == 'box-' + selected){
//function
}
});
Could do something like this:
var selected = null;
function setSelected(aSelected) {
if (selected !== null) {
// Remove existing selected click handler
$('#box-' + selected + ' .hit').off('click.selected')
}
selected = aSelected;
// Click handler for new selected el
$('#box-' + selected + ' .hit').on('click.selected', function() { });
}
I would need to see the whole context to understand,
but at the first look it seems the posted code is being run once on your page.
So if You do
var selected = something;
$('#box-' + selected + ' .hit').click(function(){
//function
});
and later on
selected = "newvalue";
this will not change program behaviour, the click event is already set for specific objects.
The other suggestion to set click handler on .hit makes a lot of sense, and then inside the handler You could check if
($(this).parent().attr('id')) == ("box-"+selected)
and only then execute Your code.

set value to jquery autocomplete combobox

I am using jquery autocomplete combobox
and everything is ok. But I also want to set specific value through JavaScript like $("#value").val("somevalue") and it set to select element, but no changes in input element with autocomplete.
Of course, I can select this input and set value directly, but is it some other ways to do that? I try set bind to this.element like this.element.bind("change", function(){alert(1)}) but it was no effects. And I don't know why.
Edit
I found a workaround for this case. But I don't like it. I have added the following code to _create function for ui.combobox
this.element.bind("change", function() {
input.val( $(select).find("option:selected").text());
});
And when I need to change the value I can use $("#selector").val("specificvalue").trigger("change");
Is this demo what you are looking for?
The link sets the value of the jQuery UI autocomplete to Java. The focus is left on the input so that the normal keyboard events can be used to navigate the options.
Edit: How about adding another function to the combobox like this:
autocomplete : function(value) {
this.element.val(value);
this.input.val(value);
}
and calling it with the value you want to set:
$('#combobox').combobox('autocomplete', 'Java');
Updated demo
I cannot find any available existing function to do what you want, but this seems to work nicely for me. Hope it is closer to the behaviour you require.
I managed a quick and dirty way of setting the value. But, you do need to know both the value and the text of the item that you want to display on the dropdown.
var myValue = foo; // value that you want selected
var myText = bar; // text that you want to display
// You first need to set the value of the (hidden) select list
$('#myCombo').val(myValue);
// ...then you need to set the display text of the actual autocomplete box.
$('#myCombo').siblings('.ui-combobox').find('.ui-autocomplete-input').val(myText);
#andyb,
i think rewrite:
autocomplete: function (value) {
this.element.val(value);
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input.val(value);
}
I really like what andyb did, but I needed it to do a little more around event handling to be able to handle triggering the a change event because "selected" doesn't handle when hitting enter or losing focus on the input (hitting tab or mouse click).
As such, using what andyb did as a base as well as the latest version of the jQuery Autocomplete script, I created the following solution: DEMO
Enter: Chooses the first item if menu is visible
Focus Lost: Partial match triggers not found message and clears entry (jQuery UI), but fully typed answer "selects" that value (not case sensative)
How Change method can be utlized:
$("#combobox").combobox({
selected: function (event, ui) {
$("#output").text("Selected Event >>> " + $("#combobox").val());
}
})
.change(function (e) {
$("#output").text("Change Event >>> " + $("#combobox").val());
});
Hopefully this helps others who need additional change event functionality to compensate for gaps that "selected" leaves open.
http://jsfiddle.net/nhJDd/
$(".document").ready(function(){
$("select option:eq(1)").val("someNewVal");
$("select option:eq(1)").text("Another Val");
$("select option:eq(1)").attr('selected', 'selected');
});
here is a working example and jquery, I am assuming you want to change the value of a select, change its text face and also have it selected at page load?
#
Attempt 2:
here is another fiddle: http://jsfiddle.net/HafLW/1/ , do you mean that you select an option, then you want to append that value to the autocomplete of a input area?
$(".document").ready(function(){
someString = "this,that";
$("input").autocomplete({source: someString.split(",")});
$("select").change(function(){
alert($(this).val()+" appended");
someString = someString+","+$(this).val();
$("input").autocomplete({source: someString.split(",")});
});
});

Changing a checkbox's state programmatically in dashcode

Okay, so I'm trying to change a checkbox's state programmatically in dashcode. I've tried:
var checkbox = document.getElementById("checkbox");
// I have tried all the following methods.
checkbox.checked = false;
checkbox.selected = false;
checkbox.value = false;
Dashboard Widgets just run on WebKit technologies, so code valid for Safari should also be valid in Dashcode. Either of the following should work:
checkbox.checked = true;
checkbox.setAttribute("checked", "true");
The fact that they are not working indicates there is a problem elsewhere in your code. I would check the line
var checkbox = document.getElementById("checkbox");
Correctly assigns an element to the checkbox variable. Also, check the id of your "checkbox" element is valid and correct (not a duplicate, doesn't have a typo, etc).
This question is one month old as I write this answer. It was probably already solved, but in any case I would like to add that if you are using Dashcode, the Checkbox part is a div which contains one label and one input, this one being the "real" checkbox.
If you inspect the html as it is loaded in Safari you will notice that "checkbox" is the type of the element.
Therefore the proper way to change the state of the checkbox would be, assuming "input" is its id (it could have a default number attached though):
document.getElementById("input").checked="true";
or whichever method you want to use.
The main point here is that you were trying to change the state of another div.
Hope it helps!
checkbox.setAttribute("checked", "checked"); // set
checkBox.removeAttribute("checked"); // remove
This question has been around a while. Regardless, the following works for us:
checkbox.childNodes[1].checked = true;
checkBox.childNodes[1].checked = false;
As pointed out in a previous answer, the way Dashcode creates these controls you need to get past the div wrapper, which has the actual ID (checkbox in this example) and set the property for the input, which is child node 1.
Looking for the actual 'id' of the input would be problematic as you have no control over what id's are assigned to the node. For example if you have two checkboxes then the first one would have 'input' as the id for child node 1 and the second one 'input1', unless, of source you have used 'input' or 'input1' as an id somewhere in your design already!
There might be another method but I have not found it yet.
I don't know which browser you used, but when I tested on FF 3.6, it works.
just put like this:
checkbox.checked = false;
while:
checkbox = document.getElementById('blablabla');
or write like that
document.getElementById('idhere').checked = false;
Maybe:
checkbox.checked = "checked";
Then:
checkbox.checked = "unchecked";
cell = row.insertCell(-1);
sel = document.createElement('input');
sel.setAttribute("type", "checkbox")
sel.setAttribute("name", "myCheckBox")
cell.appendChild(sel);
cell.getElementsByTagName('input')[0].checked = true;
I create a table, row then cell and create a checkbox within it.
I can the grab hold of the first input object and set the checked status to true.
var checkbox = document.getElementById("checkbox");
there is a problem with this line, it should be
var checkbox = document.getElementById('#checkbox");

JavaScript\JQuery - identifying if radio button value changed by click

I have a page that displays a list of records. The user can select the record status using radio buttons, e.g.:
<div id="record_653">
<label><input type="radio" name="status_653" value="new" checked/>new</label>
<label><input type="radio" name="status_653" value="skipped" />skipped</label>
<label><input type="radio" name="status_653" value="downloaded" />downloaded</label>
</div>
I am using JQuery to send the changes made by the user back to the server, where I use them to update the database. This is a simplified version of what I do:
$("#record_653").click(
function(event) {
var url = ...,
params = ...;
post(url,params);
});
The problem is that this code will create requests even if the user clicks the same button that was previously checked. What I actually want is the "on change" event, except its behavior in Internet Explorer is not very useful (e.g. here).
So I figure I somehow have to identify if the click event changed the value.
Is the old value stored somewhere (in the DOM? in the event?) so I could compare against it?
If not, how should I store the old value?
The old value is not stored someplace where you can query it, no. You will need to store the value yourself. You could use a javascript variable, a hidden input element, or jQuery's data() function.
EDIT
The jQuery data function provides access to a key-value-pair data structure as a way to store arbitrary data for a given element. The api looks like:
// store original value for an element
$(selector).data('key', value);
// retrieve original value for an element
var value = $(selector).data('key');
A more developed thought:
$(document).ready(function() {
// store original values on document ready
$(selector).each(function() {
var value = $(this).val();
$(this).data('original-value', value);
})
// later on, you might attach a click handler to the the option
// and want to determine if the value has actually changed or not.
$(selector).click(function() {
var currentValue = $(this).val();
var originalValue = $(this).data('original-value');
if (currentValue != originalValue) {
// do stuff.
// you might want to update the original value so future changes
// can be detected:
$(this).data('original-value', currentValue);
}
});
});
$('#record_653 input:radio').each(function() {
$(this).data('isChecked', $(this).is(':checked'));
$(this).click(function() {
if ( $(this).is(':checked') !== $(this).data('isChecked') ) {
// do changed action
} else {
$(this).data('isChecked', !$(this).data('isChecked') );
}
})
});
This was complicated to do in my head but I think you want something like this.
As was suggested by meder and Ken Browning, I ended up using JQuery's data() to store the previous value and check against it on every click.
Storing an "is checked" boolean for each input radio is one solution. However you need to maintain this value. So in the click event handler, in addition to changing the "is checked" of the current input, you need to find the input that was previously checked and change its "is checked" data to false.
What I chose to do instead was to store, in the parent element, the currently checked object. So my code looks something like:
$(document).ready(
function() {
// find the checked input and store it as "currChecked" for the record
$("#record_653").data("currChecked",
$(this).find("input:radio:checked")[0]);
// add the click event
$("#record_653").click( function(event) {
if ($(event.target).is("input:radio") &&
event.target !== $(this).data("currChecked"))
{
$(this).data("currChecked", event.target);
handleChangeEvent(event);
}
});
});
}
);
Thanks
I had the same problem, but with FF I managed to deal with it using the onchange event rather than the onclick.
This is exactly what I was looking for to deal with IE7. Works like a charm!
Thanks for the detailed solution!

Categories

Resources