disable-enable the hyperlinks by clicking on a button - javascript

I want to make something similar to this:
disable-enable a hyperlink by clicking on radio-buttons
but I would like to apply this method on multiple links, so I have to use the class of the elements.
Just changing the code using ".getElementsByClassName" doesn't work, and I don't understand why.
Can you explain that to me?
StackoverFlow answer for question
var link;
function disable_link() {
document.getElementsByClassName('testlink').disabled=true;
link = document.getElementsByClassName('testlink').href;
document.getElementsByClassName('testlink').removeAttribute('href');
}
function enable_link() {
document.getElementsByClassName('testlink').setAttribute("href",link);
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label>
<input type="radio" name="RadioGroup1" value="radio" id="RadioGroup1_0" onchange="disable_link();" />
Disable</label>
<br />
<label>
<input type="radio" name="RadioGroup1" value="radio" id="RadioGroup1_1" onchange="enable_link();" />
enable</label>
<br />
</p>
<a class="testlink" href="http://www.yahoo.com"> test </a>
<a class="testlink" href="http://www.yahoo.com"> test </a>
<a class="testlink" href="http://www.yahoo.com"> test </a>
<a class="testlink" href="http://www.yahoo.com"> test </a>
</form>
</body>
</html>
Even other methods are fine.
edit: Thanks to all of you for the answers.

getElementsByClassName returns a HTMLCollection, so you will have to loop over it and handle each link individually.
In this case you no longer can use temporary variable to hold disabled link href. Simple solution would be to store removed href attribute in another attribute on the corresponding element.
It can look something like this:
function disable_link() {
var links = document.getElementsByClassName('testlink');
for (var i = 0; i < links.length; i++) {
links[i].setAttribute('data-href', links[i].getAttribute('href'));
links[i].removeAttribute('href');
}
}
function enable_link() {
var links = document.getElementsByClassName('testlink');
for (var i = 0; i < links.length; i++) {
links[i].setAttribute("href", links[i].getAttribute('data-href'));
}
}
Demo: http://jsfiddle.net/5z8av0xg/

Note s in the following quote:
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.
[ http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp ]

this line wont work because it doesn't make sense which href of testclass should be set in parameter:
link = document.getElementsByClassName('testlink').href;
Actually You dont need to remove href. instead of that you can make a not_active class and toggle this class on all links is testlink class. (workd in IE11+ and others)
.not-active {
pointer-events: none;
cursor: default;
}
jquery to toggle class (handles both enabling and disabling):
function disable_link(){
$(".testlink").toggleClass("not_active")
}

Related

can I remove a line in my HTML code with javascript?

I have this code:
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>
and I want to make a javascript code to remove the div below the input field whenever I write anything in the input
..........
I tried this code:
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
var parent = field.parentNode;
parent.innerHTML = field.outerHTML;
field.value = num;
}
but it have a problem each time I make an input, I have to re-click inside the input to make it active again
check out the code here
You should not use inline HTML event attributes to wire up event handlers. That technique is 25+ years old and will not die the death it deserves because people just keep copying it from other code they've seen.
See the comments for the simple explanation:
// Add the event handler to the input in JavaScript, not in HTML
document.getElementById("myID").addEventListener("input", removeElement);
function removeElement(){
// Remove the sibling element that follows the input
document.querySelector("#myID").nextElementSibling.remove();
// Now that the element has been removed, this function is no
// longer required, so remove the event handler to prevent attempts
// to remove it again when it's no longer there. "this" refers to
// the object that caused this function to be invoked (the input
// element in this case).
this.removeEventListener("input", removeElement);
}
<div class="input">
<input type="number" id="myID">
<div>
<h3>MY TEXT</h3>
</div>
</div>
How to remove an HTML element using JavaScript ?
Given an HTML element and the task is to remove the HTML element from the document using JavaScript.
Approach:
Select the HTML element which need to remove.
Use JavaScript remove() and removeChild() method to remove the
element from the HTML document.
Exemple to remove a div :
div.parentNode.removeChild(div);
Follow this link for more information.
I hope I was able to help you.
<div class="input">
<input type="number" id="myID" >
<div id="id2">
<h3>MY TEXT</h3>
</div>
</div>
<script>
document.getElementById("myID").oninput = function() {myFunction()};
function myFunction() {
document.getElementById("id2").innerHTML="";
}
</script>
Problem with using innerHTML is you are basically using a whiteboard. You erase everything on it and you have to redraw it all. That means you would need to reset the value and focus. It is doable, just not practical.
The better thing to do would be to select the element and remove it with .remove()
var field = document.getElementById("myID");
var num = field.value;
if (num.length) {
field.nextElementSibling.remove()
}
It will work, but you will be better off using a class to hide the element. It also has the benefit that if the user deletes the text in the input, you can reshow the message. I would just hide it with a css class with toggle. I would select the div with nextElementSibling.
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
field.nextElementSibling.classList.toggle('hidden', num.length)
}
.hidden {
display: none;
}
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>

How i can show the href of all my <a> links inside a span beisde the <a>

I have the following markup, which represents a table which have <a> inside its <td>:-
now i am trying to find a way using javascript, to show the href of all the <a class="ms-listlink"> beside them.so the <td> will contain something as follow:-
Design Transfer
http://***/buisnessfunctions/pmo/progammes/136/
instead of just showing the text:-
Design Transfer
so is there a way to achieve this?
You can do this without javascript - css has a content property that can access attributes. Here's an example:
a {
display: block;
}
a:after {
display: inline-block;
margin-left: 1em;
content: attr(href);
}
Google
Zombocom
Loop through each link, read its href property and insertAfter the link.
$('.ms-listlink').each(function(){
var link = $(this).attr('href');
$(this).insertAfter('<span>'+ link +'</span>');
});
I prefer the CSS solution above, but here's the JS solution FWIW
$('.ms-listlink').each(function() {
const href = $(this).attr('href');
const $td = $(this).closest('td');
$($td).append(href);
})
I really like the CSS answer. Tiny, easy, concise. Just in case you are curious (or for some reason require a JS-only solution), here is a way to do it in plain vanilla JavaScript (no additional libraries):
<div id=container>
<a href=https://google.com >GOOGLE </a> <span></span> <br />
<a href=https://faceboook.com >FACEBOOK </a> <span></span> <br />
<a href=https://yahoo.com >YAHOO </a> <span></span> <br />
</div>
<script>
var container = document.getElementById('container');
var anchor = container.getElementsByTagName('a');
var span = container.getElementsByTagName('span');
for(var item in anchor) {
span[item].innerHTML = anchor[item].href;
}
</script>
*NOTE: If you need the url's to be a clickable part of the hyperlinks, put the span's inside the 'a' tags.

Closest li without span

I'm trying to create a selector that will grab li element and show the text. The problem is that inside li tag I have span tag and that is also displayed.
How do I grab text of closest element without some of the elements inside?
see here, I don't want the word 'Edit' to be included.
http://jsfiddle.net/ozyf87tb/
<li>This is the story of the Jungle book
<form action="" method="" class="form_edit">
<textarea class="inte" value="" name="inte"></textarea>
</form>
<span class="edit">Edit</span>
</li>
$(".edit").click( function(ev) {
var a = $(this).closest('li').text();
$('.inte').val(a);
});
http://jsfiddle.net/ozyf87tb/7/
Clone it (so you work with the clone, not in the DOM), get children, remove the children, get the text.
$(".edit").click( function(ev) {
var a = $(this).closest('li').clone().children().remove().end().text();
$('.inte').val(a);
});
The most readable way to do what you want to do is surrounding your text with a container like <span class='myText'></span>. So you could select the exact container using its class :
DEMO
<li><span class='myText'>This is the story of the Jungle book</span>
<form action="" method="" class="form_edit">
<textarea class="inte" value="" name="inte"></textarea>
</form>
<span class="edit">Edit</span>
</li>
$(".edit").click( function(ev) {
var a = $(this).prevAll('.myText').text();
$('.inte').val(a);
});
First, get a clone() of the html.
var a = $(this).closest('li').clone();
Then remove the extraneous span.
a.find('span').remove();
Then put that into the textarea.
$('.inte').val( a.text() );
This can also be rewritten into a single string, but takes away from readability.
var a = $(this).closest('li').clone().find('span').remove().end().text();
$('.inte').val( a );
jsfiddle
Use contents() and then filter your selection to return only text nodes. Then all you need to do is to trim any white-space:
var a = $.trim($(this).closest('li').contents().filter(function(){
return this.nodeType == 3;
}).text());
JSFiddle
Documentation
$.trim()
.contents()
.filter()
Node.nodeType

Duplicate Div - Remove option prevents additional Div Duplication

I'm new to using javascript and have come up against a bit of a wall where I was looking for code to duplicate a DIV. I found the following code:
<html>
<body>
<form name="myform">
<input type="button" value="Click here" onclick="duplicate()">
<div id="original">
duplicate EVERYTHING INSIDE THIS DIV
</div>
<div id="duplicater">
duplicate EVERYTHING INSIDE THIS DIV
<input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
</div>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
</html>
This works quite well. I added a Remove Div button so if the user decided they added one Div too many they would have the option to remove it. However, in testing I found if the user Remove Div all the way back to the first Div, any further Duplicate Div does not display. So the user would have to restart the page. To resolve this I tried to include an IF...ELSE.
<html>
<body>
<form name="myform">
<input type="button" value="Click here" onclick="duplicate()">
<div id="original">
duplicate EVERYTHING INSIDE THIS DIV
</div>
<div id="duplicater">
duplicate EVERYTHING INSIDE THIS DIV
<input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
</div>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
if (document.getElementById("duplicater")=="none")
{
document.getElementById("duplicater")="";
}
else
{
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
}
</script>
</body>
</html>
However, this does not work. I fully admit to being no coding guru and wouldn't be surprised if it is a simply syntax issue, but any points with this would be greatfully accepted.
Your problem is here:
this.parentNode.style.display = 'none'
This is setting the parent node (the form) to not display (which isn't the same as removing it). What you want to do is find the lastChild to the of the parent node and remove it.
Matt has your answer, I got distracted so here's a late response. In your code:
> <input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
does not "remove" the node, it just hides it. To remove the node:
<input type="button" value="Remove Div" onclick="this.parentNode.parentNode.removeChild(this.parentNode)">
Also:
> if (document.getElementById("duplicater")=="none")
getElementById returns either a DOM node with a matching ID, or null if there isn't one. Neither will ever be equivalent to the string "none", therefore the above will always return false. Which is a good thing because in the line:
> document.getElementById("duplicater")=""
You will be trying to assign to null or a DOM element, both of which are not permitted. In the case that the left hand side evaluates to null , an error will result. Where it resolves to a DOM element, anything can happen (since host objects can do what they like) but likely an error will result.

html multiselect images

I printed to the screen 16 icons (little pictures).
Now I want to be able to select icons,
and when I press a button the selected icons ids will be sent in a form.
I saw in the net only checkboxes and lists multiselect,
what's the best way to do this?
(I'm pretty new to web design)
thanks ahead!
Although jQuery isn't in your tags, you should introduce yourself to jQuery. It'll make your life easier, for what you're trying to do. Here is the basic steps both if you use jQuery and if use just Javascript:
With jQuery
Give all your icons a class and each one a unique id:
<img src='icon1.png' data-iconID=2233 class='myIcons' />).
Then bind that class to a click event
$('.myIcons').bind('click', function() {
$(this).toggleClass('selectIcon');
});
Attach form submit function to onsubmit:
<form ... onsubmit="submitForm();">
Build submitForm function:
function submitForm() {
var csvIconIds = '';
$.each($('.myIcons.selectIcon'), function (index, value) {
csvIconIds += $(value).attr('data-iconID');
});
//submit scvIconIds here along with other form data (ajax?)
}
With Javascript
Similar as above but way more complicated...
To toggle classes see this thread: How to add/remove a class in JavaScript?
To getting attributes by class see this site: http://www.actiononline.biz/web/code/how-to-getelementsbyclass-in-javascript-the-code/
This could be a way using just plain Javascript or jQuery. I prefer the jQuery version, since it separates the click handler from the markup, instead of using inline onclick handlers, which are in general discouraged.
What this does is use an input element array, which you can create by adding [] to the element name. This same technique can be used on SELECTs and other elements, since it signals to the server that an array has been submitted, as opposed to value known by a single key.
<html>
<head>
<style type="text/css">
div img {
cursor: pointer;
border: 1px solid #f00;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script>
function setFormImage(id) {
if (id != '' && !document.getElementById('input_'+id)) {
var img = document.createElement('input');
img.type = 'text';
img.id = 'input_'+id;
img.name = 'images[]';
img.value = id;
document.imageSubmit.appendChild(img);
}
}
$(document).ready(function(){
$('#jqueryimages img').click(function(){
setFormImage(this.id);
});
});
</script>
</head>
<body>
<pre><?php
if (count($_GET['images'])) {
print_r($_GET['images']);
}
?></pre>
<div style="float: left; width: 49%;">
<h1>Plain ol' HTML</h1>
1. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-1" onclick="setFormImage(this.id)"/>
<br/>
2. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-2" onclick="setFormImage(this.id)"/>
<br/>
3. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-3" onclick="setFormImage(this.id)"/>
<br/>
4. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-4" onclick="setFormImage(this.id)"/>
</div>
<div id="jqueryimages" style="float: left; width: 49%;">
<h1>jQuery</h1>
5. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-5"/>
<br/>
6. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-6"/>
<br/>
7. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-7"/>
<br/>
8. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-8"/>
</div>
<h1>Form Submit</h1>
<form name="imageSubmit" method="get">
<input type="submit" value="View Selected"/>
</form>
</body>
</html>
try this
var idArray = [];
$("#container-id img").each(function(index,value){
idArray.push($(value).attr("id"));
});
//do anything with the array

Categories