JQuery: Convert to & from textarea element - javascript

I am new to JQuery & I am attempting to do some things which I am not sure I can do in JQuery.
Can I get a HTML elements type using a JQuery(or maybe even a native Javascript) function? If so, what is the name of the function?
I want to update/set a HTML elements class attribute. Would you suggest I use just plain old setAttribute() for this or should I use a JQuery function? If I should use a JQuery function whats the name of the function?
Is there a javascript function that returns a HTML elements class? Is it this.getAttribute("class");?
More experienced JQuery Programmers: How would you improve this JQuery HTML code that attempts to change elements to textarea's then back again(some functionality is missing right now):
<html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
<!--
var STATE = 0;
function Toggle()
{
if (STATE==1) { convertToUpdatable(); STATE = 0; }
else { convertToStatic(); STATE = 1; }
}
function convertToUpdatable()
{
// Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements
// and store their HTML element type in the class attribute
// EG: Before: <p class="updatable"/> Hello this is some text 1 </p>
// After : <textarea class="updatable p"/> Hello this is some text 1 </textarea>
$(".updatable").each(function()
{
$(this).replaceWith("<textarea>"+$(this).text() +"</textarea>");
// TODO store this elements type in class attribute
// The below is guessing that there are jquery functions getType()
$(this).setAttribute( "class", $(this).getAttribute("class") + $(this).getType() );
});
}
function convertToStatic()
{
// Post: Find all HTML elements (with the class 'updatable'), check to see if they are part of another class aswell
// (which will be their original HTML element type) & convert the element back to that original HTML element type
$(".updatable").each(function()
{
// This uses javascript functions: how can I write this in JQuery
var type = this.getAttribute("class").replace("updatable","").replace(" ", "");
if (type == "") { alert("Updatable element had no type defined in class attribute"); return; }
$(this).replaceWith( type +$(this).text() + type );
$(this).setAttribute( "class", "updatable" );
});
}
-->
</script>
</head>
<body>
<p class="updatable"/> Hello this is some text 1 </p>
<b class="updatable"/> Hello this is some text 2 </b>
<i class="updatable"/> Hello this is some text 3 </i>
<input id="MyButton" type="button" value="Click me!" onclick="Toggle();" />
</body>
</html>

Here are links for your first three questions:
How can I determine the element type of a matched element in jQuery?
http://api.jquery.com/addClass/
http://api.jquery.com/hasClass/

Javascript:
your_element.className = 'some_class';
your_element.nodeName;

Related

How do I change more than one element?

EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>

remove class from an element if any of the give classes match using javascript

i have a simple javascript function which removes a class from an element. The script i am using is
function removeclass(elementId, elementClass) {
document.getElementById(elementId).className = document.getElementById(elementId).className.replace( ' '+elementClass , '' );
}
The html code i am using is
<div id="mine" class="hide show success fail">Class will be removed from here</div>
<button onclick="removeclass('mine', 'fail show success')" type="button">Remove Class</button>
now i want when click on Remove Class button it should replace the passed classes one by one if they exist in the div. How can i do that ?
You need to split elementClass into an array so you can remove each one. Also, this is easier to do using the classList property than className.
function removeclass(elementId, elementClass) {
var classes = elementClass.split(' ');
var classList = document.getElementById(elementId).classList;
classList.remove.apply(classList, classes);
}
"not-so-much-good" solution.
function removeClass(eId, klassName) {
var el = document.getElementById(eId);
klassName.split(" ").forEach(function(e){
el.classList.remove(e);
});
}
<div id="mine" class="hide show success">Class will be removed from here</div>
<button onclick="removeClass('mine', 'success show fail show')" type="button">Remove Class</button>

getting text content of specific element

I'm trying to get element text content only ignoring element's descendants, for instance if you look at this HTML:
<p>hello <h1> World </H1> </p>
for element "P" the right output should be ONLY "hello ".
I have checked the function: "element.textContent" but this returns the textual content of a node and its descendants (in my example it will return "hello world").
Thanks,
Considering this HTML:
<div id="gettext">hello <p> not this </p> world?</div>
do you want to extract "hello" AND "world"? if yes, then:
var div = document.getElementById('gettext'), // get a reference to the element
children = [].slice.call(div.childNodes), // get all the child nodes
// and convert them to a real array
text = children.filter(function(node){
return node.nodeType === 3; // filter-out non-text nodes
})
.map(function( t ){
return t.nodeValue; // convert nodes to strings
});
console.log( text.join('') ); // text is an array of strings.
http://jsfiddle.net/U7dcw/
well behind it is an explanation
$("p").clone() //clone element
.children() //get all child elements
.remove() //remove all child elements
.end() //get back to the parent
.text();
The answer i have is the same provided in couple of other answer. However let me try and offer an explanation.
<p >hello<h1>World</h1> </p>
This line will be rendered as
hello World
If you look at this code it will be as follow
<p>hello</p>
<h1>World</h1>
<p></p>
With the <p> tag you do not necessarily need the closing </p> tag if the paragraph is followed by a element.
Check this article
Now you can select the content of the first p tag simply by using the following code
var p = document.getElementsByTagName('p');
console.log(p[0].textContent);
JS FIDDLE
You can use the childNodes property, i.e.:
var p = document.querySelector('p');
p.childNodes[0]; // => hello
jsFiddle
Change your html to
<p id="id1">hello <h1> World </h1> </p>
Use this script,
alert(document.getElementById("id1").firstChild.nodeValue);
Try to provide id for the element which you want to do some operation with that.
Below is the working example, it show output as "hello" as you expected.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
alert(document.getElementById('test').innerHTML);
}
</script>
</head>
<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>
</html>
Plain texts are considered as nodes named #text. You can use childNodes property of element p and check the nodeName property of each item in it. You can iterate over them and select just #text nodes.
The function below loops over all element in document and prints just #text items
function myFunction()
{
var txt="";
var c=document.body.childNodes;
for (i=0; i<c.length; i++)
{
if(c[i].nodeName == "#text")
txt=txt + c[i].nodeName + "<br>";
};
return txt;
}
EDIT:
As #VisioN said in comments, using nodeType is much more safer (for browser compatibility) and recommended.

How can i clone array of input type file?

I want solve this topic when i read How clone value input file?
I have array of input type file
<input type="file" class = "focus_image" name="focus_image[]" >
and i want to clone value input type file of array to another input type file same below
<input type="file" class = "focus_image" name="clone[]">
I know this problem can solve with javascript but i can't implement Help me to solve this problem!
Edit
I have popup that user can add more image then user click button save in popup then popup close and i copy value input type array of file from popup to out scope popup(from focus_image to clone)
First, you have to get the element that you're concerned with. You may wish to use querySelectorAll, with the appropriate selector. Or you may do as I have, and jujst give the original input a unique id.
Next, you have to create a clone of the desired element.
Following this, you need to change the name and (if you've done as I have - giving it an id) the id.
Lastly, you need to append the clone to the DOM.
Something a little like this, perhaps?
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
var elem = byId('origElemId');
var copy = elem.cloneNode(true);
copy.setAttribute('name', 'clone[]');
copy.setAttribute('id', 'copyElemId');
document.body.appendChild(copy);
}
</script>
<style>
</style>
</head>
<body>
<input id='origElemId' type="file" class = "focus_image" name="focus_image[]" >
</body>
</html>
Try this,
HTML
<input type="file" class = "focus_image" name="focus_image[]" onChange="document.getElementById('cloned').value=this.value">
<input type="file" class = "focus_image" name="clone" id="cloned">
//Hope so this will work for you
// Put this code in your Html Page
<div id="form-content">
<div id="cloned-content">
<input type="file" class = "focus_image" name="focus_image[]" >
</div>
</div>
<a style="cursor: pointer" id="makeclone"> makeclone </a>
// This code will clone your all fields inside the div cloned-cotent
jQuery(document).ready(function() {
var cloneCounter = 1;
function makeClones() {
// clone the div
var clone = $("#cloned-content").clone(false);
// change all id values to a new unique value by adding "_cloneX" to the end
// where X is a number that increases each time you make a clone
$("*", clone).add(clone).each(function() {
if (this.id) {
this.id = this.id + cloneCounter;
}
if (this.name) {
this.name = this.name
}
});
++cloneCounter;
$("#form-content").append(clone);
}
$("#makeclone").click(function() {
alert("Clicked Fired");
makeClones();
});
});

javascript in html

i am using javascript to change the text of div tag on run time.
how can this be done..
my div tag is as:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" onclick="edit1();"/>
Div Tag
</div>
i wnt the user to input text on runtime in div and that should be displayed in div.
can someone help me..
It should be innerHTML. innerHTM is not a javascript function.
You don't get a magic variable just by having an element with an id. var something = document.getElementById('some-id')
The property is called innerHTML not innerHTM
innerHTML is a string variable not an function. Assign a value to it with =, don't try to call it with ()
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
and with proper error handling:
function edit1() {
alert('you are in edit1');
var topDiv = document.getElementById('topdiv');
if (topDiv != null) {
topDiv.innerHTML = 'hello';
} else {
alert('topdiv is nowhere to be found in this DOM');
}
}
Try document.getElementById('topdiv').innerHTML = "Hello"
To get the div you should use document.getElementById('topdiv'). There is indeed a WebKit feature, that elements with an ID are automatically expanded as global variables, but it's highly questionable, that this becomes mainstream.
Then, innerHTM should read innerHTML, and you assign directly:
foo.innerHTML = "hi there"
you should use
document.getElementById('topdiv').innerHTML = 'hello';
You should use references instead of ID's, using this.
In that case this means the node that triggers the event.
<div style="color:Blue" onmouseover="button1(this);">
<input type="button" onclick="edit1(this);"/>
Div Tag
</div>
function button1(divRef){
//divRef is the reference to the DIV
}
function edit1(inputRef){
//inputRef is the reference of the INPUT
//inputRef.parentNode is the reference to the DIV
}
function edit1() {
alert('you are in edit1');
document.getElementById('topdiv').innerHTML = 'hello';
}
This should work by specifying the id
In standard JavaScript usage you'd do as per #DarinDimitrov 's answer.
document.getElementById("topdiv").innerHTML = ('hello');
Once you're happy with JavaScript I would suggest you look at the JQuery libraries - the powerful syntax will let you write short, neat code like this:
$("#topdiv").html('hello');
Your file
<div id="topdiv" style="color:Blue" onmouseover="button1();"> Div Tag</div>
<form><input type="button" id="btndiv" value="Edit" onClick="window.open('t2.html','popuppage','width=850,toolbar=1,resizable=1,scrollbars=yes,height=700,top=100,left=100');" value="Open popup"/></form>
t2.html file
function sendValue (s){var selvalue = s.value;window.opener.document.getElementById('topdiv').innerHTML = selvalue;window.close();}
<form name="selectform"><input name="details" value=""><input type=button value="Copy input to parent opener" onClick="sendValue(this.form.details);"></form>
Got Idea from this source enter link description here

Categories

Resources