jquery does not remove element - javascript

I've a page that uses jquery mobile and I've got the following simple problem:
A webpage with a (single) link somewhere in the DOM:
<a data-theme="a" data-role="button" href="https://m.mybet.com">
Smartphone-Version nutzen</a>
And I added a button like this to the html
<input type="button" onclick="javascript:remove_link();"/>
My javascript looks like this:
<script type="text/javascript">
function remove_link() {
console.log("1")
$("a").remove();
console.log("2")
}
</script>
However, when clicking the button the chrome browser tells me:
Uncaught TypeError: Cannot call method 'remove' of null
remove_link
onclick
I also tried empty() instead, same problem. Why?

I allways use ids with javascript, is easier for me. Try this:
<a data-theme="a" id="id1" data-role="button" href="https://m.mybet.com">
Smartphone-Version nutzen</a>
<script type="text/javascript">
function remove_link() {
console.log("1")
$("#id1").remove();
console.log("2")
}
</script>

Okay, I found out. I use native javacript now:
document.querySelector( 'a' ).remove()
does the job.

Try this:
<a data-theme="a" data-role="button" href="https://m.mybet.com">
Smartphone-Version nutzen</a>
<input id="remove_link" type="button" />
<script type="text/javascript">
$('#remove_link').click(function() {
console.log("1")
$("a").remove();
console.log("2")
});
</script>

Looks like you have not loaded jQuery. Make sure you include the <script src="path/to/jquery.js"></script> before calling your function.
Without loading jQuery, your browser is calling the native $ function.
// native jQuery function
function $(id) {
return document.getElementById(id); // may return null
}
The native function may return null instead of an empty jQuery object. It is also searching for an id, rather than a css selector. In your case, an element with id 'a' rather than all anchor elements.

Related

Link to a HTML page inside a Javascript function

I want to link to a HTML file from a JavaScript on-click function. For that I used following function.
onClick: function () {
document.link("about.html");
}
But this is not working. So how can I add link inside of onClick function. Can anyone help me.
Usually I use this code:
<input type="button" value="Go to page" onclick="location.href='mypage.html'"/>
Anyway u can try:
onClick: function () {
location.href("about.html");
}
You can use the onclick property of a button element in HTML that will trigger a function when the button is pressed.
<button onclick="myFunc()">click me</button>
In your JavaScript file, you can then create the myFunc() function that will be called and executed soon after.
function myFunc() {
window.location = "otherpage.html";
}
According to W3C it's safer for cross-browser compatibility to use window.location rather than document.location.
onclick:function(){
window.navigate('your_url');
}
Try this:-
<input type="button" value="Go to page" onclick="openUrl()"/>
function openUrl() {
window.open("about.html");
//or
//window.location.href= "about.html";
}

Api JS code does not seem to react to an onclick

I've been trying to get this JS code into one of my pages in Magento. Yet it does not let me run the code.
Javascript:
<script>
function emailSend()
{
rrApiOnReady.push(function() { rrApi.setEmail($("#newsletter").val(););});
}
</script>
#newsletter is the id of an <input type="text">
The button who needs to trigger the emailSendfunction:
<div class="actions">
<button type="submit" title="<?php echo $this->__('Subscribe') ?>" class="button" onclick="emailSend()"><span><span><?php echo $this->__('Subscribe') ?></span></span></button>
</div>
I've tried $(document).ready(function() {});
I've tried different methods to get this to work.
When using alert("Hello World"); it's working fine. Anything wrong with the api's given code?
Is there anything wrong with the code?
The Chrome console says this: Uncaught SyntaxError: missing ) after argument list
I've seen that it might be an extra }? Can't seem to find it...
Any tips or tricks to get this to work?
You could try something like this:
$(document).ready(function () {
$("#ButtonID").click(function (event) {
//stuff you want to do
});
});

How can I set focus on an element in an HTML form using JavaScript?

I have a web form with a text box in it. How do I go about setting focus to the text box by default?
Something like this:
<body onload='setFocusToTextBox()'>
so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
As mentioned earlier, document.forms works too.
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
window.onload is to put focus initially
onblur is to put focus while you click outside of the textarea,or avoid text area
blur
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
</script>
If your <input> or <textarea> has attribute id=mytext then use
mytext.focus();
function setFocusToTextBox() {
mytext.focus();
}
<body onload='setFocusToTextBox()'>
<form>
<input type="text" id="mytext"/>
</form>
</body>
this example worked for me
$(document).ready(function () {
document.getElementById('TextBox').focus();
}
Try This:
$('.modal').on('shown.bs.modal', function () {
setTimeout(function() {
$("input#yourFieldId").addClass('modal-primary-focus').focus();
},
500);
});
Thought of sharing some edge cases for this subject.
If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result.
Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input

jQuery .on click event does not occur

Hi and thanks for reading. I've been trying to avoid using HTML onclick="__" references and instead putting these events in my .js file. After reading about jQuery's .click() and then .on() events, I tried to use this in my code for a button.
edit In my haste to make up a <p> that didn't have the rest of the contents, I entered "name" instead of "id". Many answers have recommended I either switch to a p[name=p+ or #p+ reference, but my main problem has been that I can't even hit the alert before the reference to the id/name. Thanks again for your answers.
HTML:
<p name="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
JS:
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("p" + $(this).attr("name")).remove();
});
});
The above code won't even get to the alert when I click the button. I've also tried referring to the button by name and ID, and going by $(document).ready($('.deleter')___.
I tried using the $(handler) format as well to have the click event be set after the document is ready. Neither way seems to work. At this point, I resorted to onclick="deleteButton()" and have a deleteButton() function in my .js file, but the function won't detect $(this) and just deletes all <p> tags.
The rest of my javascript is working. I haven't tried including this .on() at the bottom of the HTML, but I'm trying to avoid scripts in my HTML as well. For completeness' sake, I've been testing on both Chrome and Firefox, using a .jsp file to render the HTML.
Thanks again.
Edits
here's how I'm referencing my jquery and js, directly copy-pasted.
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="javascript/index.js"></script>
</head>
here is how my html looks leading up to the div where the is inserted:
<body>
<div id="wrapper">
<div id="header">Card Draw Probability Calculator</div>
<div id="main">
<div id="cardList">
<fieldset>
<legend> Select cards for probability calculation</legend>
<div id="innerCardList"></div>
Here is how the <p> is generated:
function newestCardListLineMaker() {
var $newLine = $('<p id="newestPara"><input type="checkbox" name="new" value="none"/> <input class="cardText" type="text" maxlength="30" name="newestCard" /> Quantity <input type="text" maxlength="1" class="quantityText" name="newestQuant" /><button class="deleter" id="newestDelete">Delete</button><br/></p>');
$("#innerCardList").append($newLine);
On another note, which I should have seen before as significant: the HTML that the .click or .on(click, handler) is referencing has been created by another js function.
Try using .on() function, so your code would be:
$(document).ready({
$('.deleter').on('click', function(){
//do stuff here
});
});
Even better would be this:
$(document).ready({
$('div_above_.deleter').on('click', '.deleter', function(){
// do stuff here
});
});
Hope this helps you.
I have modify your javascript code check it.
$('.deleter').click(function() {
alert('click function works');
var p="p"+$(this).attr("name");
$('p[name='+p+']').remove();
});
working demo
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>​
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).hide();
});
});​
Edited Jsfiddle
For me it works. Didn't delete the Paragraph element though so your code should look like this instead:
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
and
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).remove();
});
});
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
//alert($(this).attr("name"));
$("p[name=p" + $(this).attr("name") + "]").remove();
});
});​
The final code I used to complete the .on('click') event was:
$(document).ready(function() {
$("div#innerCardList").on("click", "button.deleter", function() {
var paraName = $(this).closest("p").attr("id");
$("#" + paraName).remove();
});
});
The HTML elements which I wanted to assign click events to were generated after the page was already loaded. I needed to delegate the events to the containing div.
Thanks for all the help and different perspectives!

unable to call click event in JS file

Below is the html code:
<input type="button" id="abc" name="TechSupport_PartsOrder" value="Open Editor" />
Below is the JQuery Code:
$('#abc').click(function () {
alert('x');
});
Now when i put the above JQuery code to JS file it does not work, while when i put the same in page it works fine. Why this is happening i don't knw.
And if i call the function onclick of button like this:
<input type="button" id="abc" name="TechSupport_PartsOrder" onclick="abc()" value="Open Editor" />
JQuery:
function abc()
{
alert('x');
}
it works well..
Wrap the code in a ready handler:
$(function() {
$('#abc').click(function() {
alert('clicked');
});
});
Did you make sure that the event handler is getting defined after the DOM has loaded? This is why jquery recommends putting all your code in
$(document).ready(function(){
//XXX code goes here
});
you're event handler is probably try to be assigned before the element has been loaded into the DOM.
Does the following solve the problem?
$(function(){
$('#abc').click(function () {
alert('x');
});
})
Your code may be getting called before '#abc' has been added to the DOM

Categories

Resources