Javascript OnFocus and OnBlue events - javascript

I want to create onfocus and onBlur events in Javascript. I have a found a solution which is in jQuery but not sure how to convert it into Javascript.
<textarea id='postitTextArea' ></textarea>
$('input,textarea').focus(function()
{
$(this).data('placeholder', $(this).attr('placeholder'))
.attr('placeholder', '');
}).blur(function()
{
$(this).attr('placeholder', $(this).data('placeholder'));
});
The above code is working fine. Any help would be appreciated.

Try like this:
var obj = document.getElementById('postitTextArea');
obj.removeAttribute('onfocus');
obj.removeAttribute('onblur');
obj.addEventListener('focus', function() {
// your js code for focus event
});
obj.addEventListener('blur', function() {
// your js code for blur event
});

var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
inputs[index].onfocus = function(){
// Your script
};
inputs[index].onblur = function(){
// Your script
};
}
//similarly for textarea

This is the JavaScript code for the jQuery code you have provided,
HTML:
<textarea id='postitTextArea' placeholder="placeholder text" onfocus="focusAction()" onblur="blurAction()"></textarea>
JS:
function focusAction(){
var target = document.getElementById('postitTextArea');
var setAttrVal = target.setAttribute('placeholder',' ');
console.log('placeholder: ' + setAttrVal);
}
function blurAction(){
var target = document.getElementById('postitTextArea');
var setAttrVal = target.setAttribute('placeholder','placeholder text');
console.log('placeholder: ' + setAttrVal);
}

Related

Stop incremental counter and disable interaction

I am trying to get the counter to stop at 0 and when it does the entire div is unclickable/disable interaction.
There is a link in the middle. So when i click 3 times I want it to be un-clickable.
edit:also it doesn't need to use Knockout. any approach, if more simple is fine.
What would be the best approach?
Fiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
Simply try adding this line
if (this.numberOfClicks() > 0)
Before
this.numberOfClicks(this.numberOfClicks() - 1);
We'll get something like that:
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
if (this.numberOfClicks() > 0)
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
See Fiddle
A bit late but give a look to my solution because I simplified a lot your code and I think you can get some value from it (for example the use of var self = this which is a best practice).
The idea behind my solution is very simple:
1) Show or hide the link or a normal text with respect to your hasClickedTooManyTimes computed variable.
empty link
<p data-bind='if: hasClickedTooManyTimes'>empty link</p>
2) Simply block the click on div if hasClickedTooManyTimes is true.
self.registerClick = function() {
if(!self.hasClickedTooManyTimes()){
self.numberOfClicks(this.numberOfClicks() - 1);
}
};
Check the Fiddle!
Let me know if this was useful to you!
Just disable the link when your count is done:
First add an id to your link:
<a id="a1" href=#> <p>empty link</p> </a>
Next disable that id when the time is right like this in your javascript:
this.hasClickedTooManyTimes = ko.computed(function() {
if (this.numberOfClicks() < 0) {
$('#a1').attr('disabled', 'disabled'); // <--- disable it
}
return this.numberOfClicks() <= 0;
}, this);
Take a look at the fiddle for JS code, stackoverflow is not validating my code section for the JS content.
HTML
<body>
<div>You have teste clicks!</div>
<div id="demo"></div>
</body>
JS
var btnObserver = (function() {
var me= this;
var clickleft = 3;
var registerClick = function() {
if(clickleft > 0) {
clickleft--;
}
};
var isCLickable = function() {
console.log(clickleft);
return clickleft !== 0;
};
return {
registerClick: registerClick,
isCLickable: isCLickable
}
})();
document.getElementById("mybtn").addEventListener("click", function(){
var message= "Hello World";
btnObserver.registerClick();
if(!btnObserver.isCLickable()) {
message= "X Blocked!";
// return false or do anything you need here
}
document.getElementById("demo").innerHTML = message;
});
Fiddle: http://jsfiddle.net/qkafjmdp/

Changing text inside of a dynamically created element

I want to change the text inside of an element for dynamically created elements. i = 2 because that's Why is it not working?
var loanName = function() {
for(var t=1; t < i; t++) {
$('body').on('keyup', '.loanNameV'+t, function () {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
};
$('body').on('keyup', '[class^="loanNameV"]', function () {
var numbesideclass = ($(this).attr('class').split('loanNameV'))[1];
var loanN = $(this).val();
$('.nameLoan'+numbesideclass).text(loanN);
});
Note: this code will work if you don't have another class for loanNameV elements like class="loanNameV1 anotherclass anotherclass" in this case this code will not work as expected

multiple select get recently selected option value

I want to know last or recently selected option value for dropdown
I have tried following code in django :
<script type="text/javascript">
django.jQuery(document).ready(function(){
django.jQuery("#id_emuhibah_issue").on("click", function(e){
console.log(" click -------");
console.log(django.jQuery(this).val());
console.log(this.value);
});
});
django.jQuery(document).ready(function(){
django.jQuery("#id_emuhibah_issue").on("change", function(e){
console.log(" chage -------");
console.log(django.jQuery(this).val());
console.log(this.value);
});
});
</script>
seems there is no luck to find out last selected value
Can anyone suggest solution for above case?
Just remove the click function and use only on.("change" function..) one function with one "document ready"
Here how I have manage to handle the case:
<script type="text/javascript">
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
var old_selected_issues = [];
django.jQuery(document).ready(function(){
django.jQuery("#id_issue").on("change", function(e){
var new_selected_issues = django.jQuery(this).val();
if(new_selected_issues != null){
var diff = new_selected_issues.diff(old_selected_issues);
old_selected_issues = new_selected_issues;
if(diff.length){
//perform the job on last selected option
var lang = window.location.pathname.slice(1,3)
django.jQuery("#issue_iframe").attr('src', '/'+lang+'/admin/'+diff[0]+'/');
}
else{
django.jQuery("#issue_iframe").attr('src', '');
}
}
else
{
old_selected_issues = [];
django.jQuery("#issue_iframe").attr('src', '');
}
});
});
</script>
Please let me know, in case of any other possible solution

Bind function to the event "onclick" of the elements of an array of buttons

Preamble: I'm Italian, sorry for my bad English.
This is my problem:
I want to assign a function to a set of buttons.
I need to send a parameter to the function.
this is the code that I've tried:
function test(atxt) {
var buttons = $('.tblButton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onClick(sayHello(atxt));
}
}
function sayHello(txt){alert('hello' + txt)};
...getting the following error:
Uncaught TypeError: Object #<HTMLButtonElement> has no method 'onClick'
can you tell me where I went wrong and how can I fix it?
EDIT: I need iteration because I need the 'id of the button as a parameter of the function so i need to do buttons[i].onClick(sayHello(buttons[i].id))
buttons[i].onClick(sayHello(atxt));
Supposed to be
$(buttons[i]).on('click', function() { sayHello(atxt) });
If you want to get the current button id then I think you are looking for this..
for (var i = 0; i < buttons.length; i++) {
$(buttons[i]).on('click', function() { sayHello(this.id) });
}
If you want to iterate through all of the buttons then you have to do that with .each() handler of the jquery:
$(function(){
$(".tblButton").each(function () {
$(this).click(function(){
alert($(this).attr('id'));
});
});
});
checkout the jsbin: http://jsbin.com/usideg/1/edit
Would this not work for your example: Do you have another reason for the iteration?
function test(atxt) {
$('.tblButton').on('click',function(){sayHello(atxt);});
}
function sayHello(txt){alert('hello' + txt)};
OR optionally if the elements are static and present:
function test(atxt) {
$('.tblButton').click(function(){sayHello(atxt);});
}
function sayHello(txt){alert('hello' + txt)};
Alternate approach: just change
to this style:
var txt = "fred";
var atext = "hello" + txt;
function sayHello(atext) {
alert(atext);
}
$('.tblButton').on('click', function() {
sayHello(atext);
});
//below here just to demonstrate
$('.tblButton').eq(0).click();//fires with the fred
txt = "Johnny";// new text
atext = 'hello' + txt;
$('.tblButton').eq(1).click();//fires the Johnny
see it working here:
http://jsfiddle.net/dFBMm/
SO based on your note:
this markup and code:
<button class="tblButton" id="Ruth">Hi</button>
<button class="tblButton" id="Betty">Hi again</button>
$('.tblButton').on('click', function() {
alert("Hello "+$(this).attr("id"));
});
$('.tblButton').eq(0).click();//fires with the Ruth
$('.tblButton').eq(1).click();//fires the Betty
http://jsfiddle.net/dFBMm/1/

Event doesn't get added in a for-loop

This is the html. If a link is clicked I want to replace the span-element in front of it with some text.
<p><span id="sp1">that1</span> Update1</p>
<p><span id="sp2">that2</span> Update2</p>
<p><span id="sp3">that3</span> Update3</p>
<p><span id="sp4">that4</span> Update4</p>
<p><span id="sp5">that5</span> Update5</p>
As you can see, my idea was to give the spans en the anchors identical id's and a number.
In my jquery-code I loop through all the anchor-elements, give them a click-event that causes the span-element in front of it to be replaced.
<script type="text/javascript" >
$(document).ready(function() {
var numSpans = $("span").length;
for (n=0;n<=numSpans;n++) {
$("a#update" + n).click(function(e){
$('span#sp' + n).replaceWith('this');
e.preventDefault();
});
}
});
</script>
For some reason this does not work.
What am I doing wrong?
The problem with your original code is that you're creating a closure on the variable n. When the event handler is called, it is called with the value of n at the point of invocation, not the point of declaration. You can see this by adding an alert call:
$(document).ready(function() {
var numSpans = $("span").length;
for (n = 1; n <= numSpans; n++) {
$("a#update" + n).click(function(e) {
alert(n); //Alerts '6'
$('span#sp' + n).replaceWith('this');
e.preventDefault();
});
}
})
One way to fix this is to create a closure on the value of n in each iteration, like so:
$(document).ready(function() {
var numSpans = $("span").length;
for (n = 1; n <= numSpans; n++) {
$("a#update" + n).click(
(function(k) {
return function(e) {
alert(k);
$('span#sp' + k).replaceWith('this');
e.preventDefault();
}
})(n)
);
}
})
However, this is messy, and you'd do better to use a more jQuery-y method.
One way to do this would be to remove the ids from your code. Unless you need them for something else, they're not required:
<p><span>that1</span> Update1</p>
<p><span>that2</span> Update2</p>
<p><span>that3</span> Update3</p>
<p><span>that4</span> Update4</p>
<p><span>that5</span> Update5</p>
jQuery:
$(function() {
$('a.update').live('click', function() {
$(this).siblings('span').replaceWith("Updated that!");
});
});
jsFiddle
Don't create functions in a loop. With jQuery, there's no need for an explicit loop at all.
$(function()
{
$('span[id^=sp]').each(function(n)
{
$('#update' + n).click(function(e)
{
$('#sp' + n).replaceWith(this);
return false;
});
});
});
Demo: http://jsfiddle.net/mattball/4TVMa/
You can do way better than that, though:
$(function()
{
$('p > a[id^=update]').live('click', function(e)
{
$(this).prev().replaceWith(this);
return false;
});
});
Demo: http://jsfiddle.net/mattball/xySGW/
Try this:
$(function(){
$("a[id^='update']").click(function(){
var index = this.id.replace(/[^0-9]/g, "");
$("span#sp" + index).replaceWith(this);
e.preventDefault();
});
});

Categories

Resources