jQuery div class changes - javascript

#myDiv is a clickable box, if #myDiv is clicked, there is a class .opened will be added. my jQuery reads
if ($('#myDiv').hasClass('open')){
var myValue = "1";
}else{
var myValue = "2";
}
Apparently, after the page completed loaded, myValue always equals 2, but after clicking #myDiv, myValue is still 2. what event should I use to detect whether my elements change? I'd like to support IE7+ as well. thanks!

try this solution : http://jsfiddle.net/charaf11/Emv8L/
function containOpen(){
if ($('#myDiv.open').length==1){
var myValue = "1";
}
else{
var myValue = "2";
}
}

You would have to rerun the code, there is no way for that code to change just because a class has been added/removed.
So when the click happens you would need to call a function that will set the value.

In your click event listener, suscribe your element a custom trigger $('#myDiv').trigger('openedClassAdded').
Then
$('#myDiv').on('openedClassAdded', function () {
myValue = '2';
});

Related

javascript onclick set to false

document.getElementById("btn2").onclick = false;
I did this to stop getting on click event after the first one and when I want to set it back to normal
document.getElementById("btn2").onclick = True;
it does not take click events
You could always disable the button, like this:
document.getElementById("btn2").disabled = true;
This sets the disabled attribute to true, therefore stopping the onClick function from being called when the user clicks the button.
Declare a variable boolean and change using logical not operator (!: see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT), example:
let toggle = true;
let button = document.querySelector('button');
let result = document.querySelector('span');
button.onclick = () => {
toggle = !toggle;
result.textContent = `Your switch to ${toggle}`;
}
<button>Click me</button>
<span></span>
You may not set onclick event as True instead try this way.
const setEvent = (enable) => {
if(enable){
document.getElementById("btn2").addEventListener('click', onClickEvent);
}
else{
document.getElementById("btn2").removeEventListener('click');
}
}
function onClickEvent(){
//Your actual event when clicking the button
}
//Now enable or disable the event as follows
setEvent(true); //Will attach the event
setEvent(false); //Will remove the event
Make sure you call setEvent(true) once only, because it can attach multiple events.

How to link the variable for the function to the button's variable?

Im new to javascript, is there any way to link my function's var to the button so that the function can be executed properly.I cant seem to link the function's variable to the button's id or even the button itself.
//My button
var btn1 = document.createElement('button');
btn1.textContent = questions[0].A
btn1.id = 'optionA'
document.body.appendChild(btn1);
btn1.addEventListener('click', fSubmit);
//My Function
var score=0;
function fSubmit(){
var correctanswer=btn1;
if(correctanswer.checked==true){
score++;
alert("Answer is correct! "+"Your Score is now "+score++)}
else{
alert("Answer is incorrect!")}
}
what I think you are trying to say is that you want to bind the "correctness" of a button's data to the score. What I would do is add a custom data attribute to each button containing 'true' or 'false' value for that button.
Like so:
btn1.dataset.correctOrNot = true
Then you test that value in your fSubmit function:
if (btn1.dataset.correctOrNot === true) {
// etc. etc.
}

How do Enable/Disable linkbutton in javascript?

I have a link button in the page like:
<asp:LinkButton ID="edit" runat="server" OnClick="edit_Click" Enabled="False">ویرایش</asp:LinkButton>
I want Enable/Disable this in javascript.
I use this code but set visible
var objedit = document.getElementById('<%= edit.ClientID.ToString() %>');
objedit.style.display = "none";
I use this code but not enable
if (count == 1) {
objedit.disabled = false;
} else {
objedit.disabled = true;
}
I can click but link button is disabled.
This link should give you everything you need. You can't really "disable" a linkbutton because its just a link with some javascript attached. Basically, you need to reassign the click handler to something that returns void or false.
You can refer to the ID of the link with the following script:
<script runat="server">
var a = document.getElementById('<%= edit.ClientID.ToString() %>')
</script>
So, is this what you want?
http://jsfiddle.net/hzaR6/
http://jsfiddle.net/hzaR6/2/ -- UPDATED, tested in Chrome and Firefox
The UPDATED way
You can use a class name to define disabled element, for which you can have more control on their styles ... etc.
$("#link").toggleClass("disabled"); //This will simply toggle the class
and for the css
#link.disabled{
z-index:-1; /*Make it not clickable*/
position:relative;
opacity: .5; /*Lighter*/
}​
You can do whatever you want here.
The good old form element way
$("#edit").attr("disabled", false);
-or-
document.getElementBy("edit").disabled = false;
This will disable any form element. If you want to enable them, just change false to true.
var a = document.getElementBy("edit").disabled;
a will be true if the element is disabled. Otherwise it will be false.
To disable element:
document.getElementById('<%# edit.ClientID %>').disabled = 'disabled';
//.ToString() is not necessary; ClientID is a string.
To re-enable:
document.getElementById('<%# edit.ClientID %>').disabled = '';
Of course, it can be done after document (DOM) is loaded.
try this
var objedit = document.getElementById("edit"); //not editid (editid is a variable)
objedit.disabled = true; //if I'm not mistaken its true/false or disabled
document.getElementById("lnk").style.display = "none";

Not working my javascript onblur function

I am having some problems with a javascipt function which I'm working on.
Here is what I am trying to do with the function:
I have a table element with a given value, and when there is a click on it, it calls my javasript function which is supose to appendChild an INPUT element with the value of the element, so the user can change that value. I want the INPUT element to call a function whit the onblur() event, so the modified value could be display again on the table element.
My problem is that the element does not respect the onblur() event. The function is executed right after the Input element is created, and does not wait to be an onblur() event.
Here is the code of the two functions:
var elemento = true;
function prueba(clave,cantidad) {
if(elemento){
var percent = document.getElementById('porciento' + clave);
percent.innerHTML = "";
var input = document.createElement("input");
input.setAttribute('type','text');
input.setAttribute('size','5');
input.setAttribute('value',cantidad);
input.setAttribute('id','child'+clave);
percent.appendChild(input);
input.focus();
child = document.getElementById("child" + clave);
child.onblur = blurPrueba();
}
}
function blurPrueba() {
if(elemento)
alert("Hello");
}
The alert is displayed without being an onblur()
Does anyone knows why this is happening???
Your problem is: child.onblur = blurPrueba(), where you execute blurPrueba immediately. Should be a reference: child.onblur = blurPrueba
Changing the line, you tell the browser: "on blur for the child element, activate the blurPrueba function".
If you use blurPrueba() you activate the function and assign it's result to the blur event, blurPrueba() doesn't return anything. So your line actually says: "onblur = undefined"
In summary, if you want the browser to handle an event (here blur) you need to provide a reference to the handler function (here blurPrueba).
Change
child.onblur = blurPrueba();
to
child.onblur = function(){blurPrueba()};

Detect programmatical changes on a html select box

Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed

Categories