get the id attribute from the paragraph which has been right-clicked - javascript

Suppose that I have a text with this html markup:
<p id="myId">Some text <span>some other text</span></p>
How can I get the value of the id when I right-click anywhere on the paragraph?
Update:
I'm just passing the value to a function, which I do not mention so as to not complicate it.

write a mousedown handler for p then
$('p').on('mousedown', function(e){
if(e.which== 3){
alert(this.id)
}
})
Demo: Fiddle

Here is the function:
$('#myId').on('mousedown',function(event) {
if(event.which == 3){
var i = $(this).attr('id');
alert(i);
}
});
event.which() reports 1,2,or 3 depending on which button was clicked.
Read here mode details http://api.jquery.com/event.which/

Pure JavaScript version:
var myp = document.getElementsByTagName("p");
for(var i =0;i < myp.length;i++){
myp[i].addEventListener("mousedown",function(e){
if(e.which == 3){
console.log(this.id);
}
},false);
}

Related

linking an onkeypress event with an if else statement?

I am having an issue linking an event to an if else statement. I was able to get an onkeypress event that changed the html content but I am having issues getting the content of what key was pressed after the event to run some code if they pressed a certain key. If you could help me figure out why my code isn't working that would be great. I am getting no syntax errors. I want it to console.log when I press the key "h".
HTML
<p>Guess what letter I'm thinking of!</p>
<br/ >
<div>Wins: </div>
<br/ >
<p id="losses">Losses: </p>
<br/ >
<p>Guesses Left: </p>
<br/ >
<p>Your Guesses so far: <span id="change"></span></p>
<br/ >
Javascript
window.onload = function() {
var guess = document.body.onkeypress = function(event){
document.getElementById("change").innerHTML = String.fromCharCode(event.keyCode);
}
function test(){
var letter = document.getElementById('change');
if(letter.innerHTML==="h"){
console.log('hi');
} else {
console.log("nothing");
}
}
}
This work for me i did not found in your code the invoke of test function so i wrapped in the onkeypress
var guess = document.body.onkeypress = function(event){
console.log(event);
document.getElementById("change").innerHTML =
String.fromCharCode(event.keyCode);
var letter = document.getElementById('change');
if(letter.innerHTML==="h"){
console.log('hi');
} else {
console.log("nothing");
}
};
<input> elements don't have any HTML content, so innerHTML always returns an empty string.
You can get the value of the textbox (not just the character, if any, that the user pressed) with .value.

Javascript onClick Globally

I have a web application with many forms that submit data to a MySQL Database.
On all pages i have include 'settings.php'; so whatever i put in there will be on every page (CSS Links, JS Code etc)
Whats the best JS Code i can put in my settings.php file to put an "onClick" event on every single button on all pages.
I want it to do this:
onClick="this.disabled=true; this.value='Please Wait…';"
So on all forms within the site, every button that is clicked will display the Please Wait... text until the form is submitted
Clearly most of the people answering this question have never heard of event delegation.
window.addEventListener("click",function(e) {
var t = e.srcElement || e.target;
if( !t.tagName) t = t.parentNode;
if( t.tagName == "INPUT" && t.type.toLowerCase() == "submit") {
t.disabled = true;
t.value = "Please wait...";
}
},false);
You really shouldn't be using onClick=... Instead, bind the actions via JS:
document.getElementById('element-id').onclick=function(){
alert('Hello World');
}
Something like this ought to do it:
(function() {
var buttons = document.getElementsByTagName('button');
for (var i=0,len=buttons.length; i<len; i++) {
buttons[i].addEventListener('click', function() {
this.disabled = true;
this.innerHTML = "Please Wait...";
});
}
})();
http://jsfiddle.net/ryanbrill/5WYN9/
// very simple with jQuery
$(document).on('click', 'button,input[type="button"],input[type="submit"]', function (e) {
var $this = $(this).prop('disabled', true);
if ($this.is('button')) {
$this.html('Please wait...');
} else {
$this.val('Please wait...');
}
});

Modifying HTML elements using jquery

I am trying to use jquery to add and remove a class from <li> elements according to a variable's value ( i ).
Here is a jsfiddle of what I have done so far http://jsfiddle.net/LX8yM/
Clicking the "+" increments i by 1 ( I have checked this with chrome's javascript console ).
One should be able to click "+" and the class .active should be removed from and added to the <li> elements accordingly.
...I can get the first <li> element to accept the class, that's all...
No need for if statements:
$(document).ready(function (){
$('#add').click(function (){
$('.numbers .active').removeClass('active').next().addClass('active');
});
});
jsfiddle
Do note that I added an 'active' class to first list item. You could always do this via JS if you do not have control over the markup.
Your if..else.. is hanging in document.ready. Wrap the increment inside a function and call it respectively.
Like
$(document).ready(function (){
//variable
var i = 1;
//if statments
function incre(i){ // wrap into a function and process it
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
}
//change i
$('#add').click(function (){
incre(i++); // pass it as a parameter
});
});
Working JSFiddle
This would be easier:
$(document).ready(function(){
var i = 0; // set the first value
$('#something').click(function(){
i++; // every click this gets one higher.
// First remove class, wherever it is:
$('.classname').removeClass('classname');
// Now add where you need it
if( i==1){
$('#one').addClass('classname');
} else if( i==2){
$('#two').addClass('classname');
} else if( i==3){
$('#three').addClass('classname');
}
}):
});
See this code. Initially you have to add class to one.
$(document).ready(function (){
//variable
var i = 1;
$('#one').addClass('active');
//if statments
//change i
$('#add').click(function (){
i++;
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
});
});
It's being called only once, not in the click event function. This edit of your fiddle works: http://jsfiddle.net/LX8yM/2/
put it in the
'$('#add').click(function (){}'

How to match children innerText with user input using jQuery

I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});

Why is this javascript not working - select box if

I have this code on my site. The idea is to hide a specific class when a specific select box value is selected.
This is my code
$(document).ready(function(){
var txt = 'Marketing';
$("div.ginput_container select#input_3_1 option").each(function(){
if($(this).val()==txt){
$('.mar').hide();
}
});
});
The result I'm getting is .mar class being hidden as soon as the page is loaded. I can't see the error, I have also tryied with
var num = 1
but I have the same issue.
$(document).ready(function() {
var txt = 'Marketing';
$("#input_3_1").change(function () {
if ( this.value == txt ) $('.mar').hide();
});
});
Here's the fiddle: http://jsfiddle.net/9Cyxh/
If you want to show $('.mar') when a different option is selected, use toggle instead:
$('.mar').toggle( this.value != txt );
Here's the fiddle: http://jsfiddle.net/9Cyxh/1/
If you want this to also run on page load (before an option is manually selected), trigger the change event:
$(document).ready(function() {
var txt = 'Marketing';
$("#input_3_1").change(function () {
$('.mar').toggle( this.value != txt );
}).change();
});​
Here's the fiddle: http://jsfiddle.net/9Cyxh/2/
You don't need the loop in the first place
Attach your select to the change() event handler and that should be it..
$(document).ready(function(){
$("select#input_3_1").on('change', function() {
var txt = 'Marketing';
if(this.value === txt){
$('.mar').hide();
};
}).change()
});
If you only want to hide ".mar" class when the value is changed and it equals "Marketing" try
$("#input_3_1").change( function() {
if( $(this).val().toUpperCase() === "MARKETING" ) {
$(".mar").hide();
}
});
Demo here
$("#input_3_1").change(function(){
if ($("#input_3_1").val()=='Marketing'){
$(".mar").hide();
}
});

Categories