I got a form where I want to dynamically add input fields, if the users clicks on a "add more" button. At the moment it works to create the buttons on click, but the buttons do no get created at the position where I want them to be. Here is my HTML Code Snippet:
window.addEventListener("load", function() {
var addMoreButtons = document.querySelectorAll("#add-more1, #add-more2");
addMoreButtons.forEach(function(button) {
button.addEventListener("click", function() {
console.log(button);
// Create a div
var div = document.createElement("div");
// Create a text input
var text = document.createElement("input");
text.setAttribute("type", "text");
text.setAttribute("name", "More");
text.setAttribute("placeholder", "Weitere hinzufügen");
// add the file and text to the div
div.appendChild(text);
//Append the div to the container div
document.querySelector(".buttonTest").appendChild(div);
});
});
});
<div class="user-details">
<div class="input-box">
<span class="details">Stärken</span>
<input type="text" placeholder="Stärken, z.B. 'Kommunikativ'" id="strenghts">
<div class="buttonTest">
<button type="button" class="add-more" id="add-more1">+ Weitere
hinzufügen</button>
</div>
</div>
<div class="input-box">
<span class="details">Technische Fähigkeiten</span>
<input type="text" placeholder="Technische Fähigkeiten, z.B. 'JavaScript'" id="tech">
<div class="buttonTest">
<button type="button" class="add-more" id="add-more2">+ Weitere hinzufügen</button>
</div>
</div>
</div>
Now every time when the first (#add-more1) or second (#add-more2) button is clicked, the input field gets created below the first button. But I want the input fields to appear where the button was clicked. For example:
If the first button is clicked I want the input field to be created below the first button. And if the second button is clicked I want the input field to be created below the second button and not below the first button.
Thanks for your help! :)
You need to use parentElement
https://www.w3schools.com/jsref/prop_node_parentelement.asp
Example:
window.addEventListener("load", function() {
var addMoreButtons = document.querySelectorAll("#add-more1, #add-more2");
addMoreButtons.forEach(function(button){
button.addEventListener("click", function() {
console.log(button);
// Create a div
var div = document.createElement("div");
// Create a text input
var text = document.createElement("input");
text.setAttribute("type", "text");
text.setAttribute("name", "More");
text.setAttribute("placeholder", "Weitere hinzufügen");
// add the file and text to the div
div.appendChild(text);
//Append the div to the container div
button.parentElement.appendChild(div);
});
});
});
<div class="user-details">
<div class="input-box">
<span class="details">Stärken</span>
<input type="text" placeholder="Stärken, z.B. 'Kommunikativ'" id="strenghts">
<div class="buttonTest">
<button type="button" class="add-more" id="add-more1">+ Weitere
hinzufügen</button>
</div>
</div>
<div class="input-box">
<span class="details">Technische Fähigkeiten</span>
<input type="text" placeholder="Technische Fähigkeiten, z.B. 'JavaScript'" id="tech">
<div class="buttonTest">
<button type="button" class="add-more" id="add-more2">+ Weitere hinzufügen</button>
</div>
</div>
</div>
I have simplified your code somewhat, using event delegation and [element].insertAdjacentHTML to add a text input element. For the new text input element, a copy of the old one is used. Using insertAdjacentHTML gives you control over the placement of the new element (here: after the div containing the clicked button, cf afterend).
document.addEventListener(`click`, handle);
function handle(evt) {
const bttn = evt.target.closest(`.buttonTest`);
if (bttn) {
const inputElemCopy = bttn.closest(`.input-box`)
.querySelector(`input`).cloneNode(true);
inputElemCopy.name = `${inputElemCopy.id}_more`;
inputElemCopy.removeAttribute(`id`);
bttn.insertAdjacentHTML(
`afterend`,
`<div>${inputElemCopy.outerHTML}</div>`);
}
}
<div class="user-details">
<div class="input-box">
<span class="details">Stärken</span>
<input type="text" placeholder="Stärken, z.B. 'Kommunikativ'"
id="strenghts">
<div class="buttonTest">
<button type="button" class="add-more" id="add-more1">+ Weitere
hinzufügen</button>
</div>
</div>
<div class="input-box">
<span class="details">Technische Fähigkeiten</span>
<input type="text" placeholder="Technische Fähigkeiten, z.B. 'JavaScript'"
id="tech">
<div class="buttonTest">
<button type="button" class="add-more" id="add-more2">+ Weitere
hinzufügen</button>
</div>
</div>
</div>
Related
I have multiple html forms similar to the one below
<div class="container">
<div class="card">
<div class="card-header bg-danger">
<h3 class="card-title">Form Four</h3>
</div>
<div class="card-body">
<div class="errors">
<!-- Error messages can go here -->
</div>
<form novalidate>
<div>
<label for="password">Password : </label>
<input type="text" name="password" id="password" class="password" />
</div>
<div>
<label for="requiredPassword">Required and Password : </label>
<input type="text" name="requiredPassword" id="requiredPassword" class="required password" />
</div>
<div>
<input type="submit" name="submitBtn" value="Validate" />
</div>
</form>
</div>
</div>
</div>
I am not allowed to change them. The issue I am having is that I can't get my event listeners to work. I am trying to have the button clicked for the specific form only validate that form and not the others.
This is what I have been trying to possibly work with based on other projects I have done with multiple buttons
document.querySelectorAll("input[name=submitBtn]").forEach(item => {
item.addEventListener('click', isAllValid)
//isAllValid is a function to check the inputs in the form
});
This isn't working, and I really need help trying to find out how to make this work. Thank you!
To find the form that belongs to the button, inside isAllValid, you can do this:
function isAllValid(event) {
const btn = event.target;
const form = btn.closest('form');
// ...
}
One of the attributes of form elements is form which returns a reference to the form to which each of these elements belongs.
See the following example with multiple forms.
var buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", (event) => {
event.preventDefault();
var msg = event.currentTarget.textContent;
var form = event.currentTarget.form;
console.log("'" + msg + "' clicked (" + form.id + ")");
return false;
});
});
button {
margin: 0.5rem;
}
<section>
<form id="firstForm" name="firstForm">
<button id="firstFormButton1">Button 1 (Form 1)</button>
<button id="firstFormButton2">Button 2 (Form 1)</button>
<button id="firstFormButton3">Button 3 (Form 1)</button>
</form>
</section>
<section>
<form id="secondForm" name="secondForm">
<button id="secondFormButton1">Button 1 (Form 2)</button>
<button id="secondFormButton2">Button 2 (Form 2)</button>
<button id="secondFormButton3">Button 2 (Form 2)</button>
</form>
</section>
<section>
<form id="thirdForm" name="thirdForm">
<button id="thirdFormButton1">Button 1 (Form 3)</button>
<button id="thirdFormButton2">Button 2 (Form 3)</button>
<button id="thirdFormButton3">Button 3 (Form 3)</button>
</form>
</section>
JavaScript:
var editBtn = document.getElementById('editBtn');
var saveBtn = document.getElementById('saveBtn');
var textAreaHtml = document.getElementsByTagName("textarea");
editBtn.addEventListener('click', function (e) {
textAreaHtml[0].removeAttribute('readonly');
textAreaHtml[0].readOnly = 'false';
});
saveBtn.addEventListener('click', function (e) {
textAreaHtml[0].removeAttribute('readonly');
textAreaHtml[0].readOnly = 'true';
});
Html:
<div class="panel-body">
<div>
<input type="text" name="apexClass" id="autocomplete" placeholder="Type the name of the Apex class you want to edit"/>
</div>
<div class="btn-group-vertical" style="padding: 1%">
<button type="button" class="btn btn-primary" id="editBtn">Edit</button>
</button>
</div>
<div class="tab-content" align="left">
<div id='error' style='display:none'>{{apexClassWrapperError.message}}</div>
<div>{{apexClassWrapper.name}}</div>
<pre class="prettyprint">
<code class="language-java">
<textarea ng-model="apexClassWrapper.body" id="apexBody" readonly="true">{{apexClassWrapper.body}}</textarea>
</code>
</pre>
</div>
<button type="button" class="btn btn-primary" id="saveBtn" ng-click="postdata(apexClassWrapper)">Save</button>
</div>
I have two buttons, save and edit. I have placed event listener for Edit and save to make text area as editable, but this is not working. I am not able to edit the TextArea in the UI? Is there something I am missing?
With some slight tweaking to your click event handlers, you should be in business.
editBtn.addEventListener('click', function (e) {
textAreaHtml[0].removeAttribute('readonly');
});
saveBtn.addEventListener('click', function (e) {
textAreaHtml[0].setAttribute('readonly', true);
});
Your edit button was setting readOnly to false, but readonly is a boolean attribute. When it is present it makes the textarea readonly regardless of if it has a true or false value.
Instead of readonly, use the HTML attribute contenteditable!
I have never used readonly but by toggling the boolean on contenteditable you should be cookin!
https://www.w3schools.com/tags/att_contenteditable.asp
I am trying to create a search using ajax and mysql and placing the returned data into a div. I am following a tutorial on youtube and so far so good, however I am trying to pass in dummy data into the div but it isn't appearing.
This here is my jquery
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#search').text(data);
});
}
});
This is my html
<div class="container">
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" method="POST">
<input type="text" name="search" id="search" class="form-control" placeholder="Search">
</form><!-- /form -->
<button class="btn btn-lg btn-primary btn-block btn-signin" value= "search" type="required" id="submit" name="submit">Search</button>
</div><!-- /card-container -->
<div class="row">
<div class="col-md-4">
<div id="search"></div>
<div class="caption">
<p></p>
</div>
</div>
When the user clicks search the content from the searching.php file should appear in the div. Currently in the searching.php file it just has echo"content";. It should have "content" in the div but it isn't appearing in the web browser and there are no errors. Within the network in inspect element the name is searching.php and the status is ok. Not sure where I am going wrong, any help would be grateful.
You have multiple id="search" elements in your HTML. So this isn't going to know which one you mean:
$('#search')
It's probably trying to set the "text" of the <input>, which doesn't have a "text" (it has a "value"). Correct the HTML. Either change the <input> or the <div> to have a unique id. (And, of course, update your jQuery selectors as well as anything else targeting these elements.)
don't use same id (search) for both input and div
change the id in html
<div class="container">
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" method="POST">
<input type="text" name="search" id="search" class="form-control" placeholder="Search">
</form>
<button class="btn btn-lg btn-primary btn-block btn-signin" value= "search" type="required" id="submit" name="submit">Search</button>
</div><!-- /card-container -->
<div class="row">
<div class="col-md-4">
<div id="searchText"></div>
<div class="caption">
<p></p>
</div>
</div>
and javascript
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#searchText').text(data);
});
}
});
.text not work with input
use val() instead of text() for input
$('#search').val(data);
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<button id="btn1">Set Text</button>
<p id="test2">This is another paragraph.</p>
<button id="btn2">Set HTML</button>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button id="btn3">Set Value</button>
What should i do if i need to replace the "test test" message with custom one using JavaScript?
<div class="outputmsg_container" style="" id="output_messages"><
button class="btn btn-icon close icon-cross" onclick="GlideUI.get().clearOutputMessages(this); return false;">
<span class="sr-only">Close Messages"</span>
</button>
<div class="outputmsg_div">
<div class="outputmsg outputmsg_error notification notification-error"><img class="outputmsg_image" src="images/outputmsg_error_24.gifx" alt="">
<span class="outputmsg_text">test test</span>
</div>
</div>
</div>
Use innerHTML to change the HTML inside an element.
<label for="newhtml">HTML (or text) to be inserted inside div:</label>
<br/>
<input type="text" id="newhtml"/>
<br/>
<input type="button" id="change" value="Insert" onClick="change()"/>
<br/>
<span id="container"></span>
<script>
function change(){
document.getElementById("container").innerHTML = document.getElementById("newhtml").value;
}
</script>
Here is an example to do this with jquery.
$('.outputmsg_text').html("YOUR CUSTOM TEXT")
Here's an example JSFiddle (REQUIRE JQUERY)
<button id="change">Change Text</button>
<div id="div">
Some text
</div>
<script>
$("#change").click(function(){
var name = prompt("What text shoud it be?");
if(name){
$("#div").html(name);
}
});
</script>
In the markup, i have several divs with same id and inside those divs there are paragraphs and buttons. Now when a button is clicked, i want to get the value of a corresponding paragraph tag under the same div as that particular button. How can i do this with jQuery? The markup is as followed:
<div class="col-sm-5 narrow">
<p id="title">Jhon123</p>
<p id="text">This is the status of jhon</p>
<p>posted at 12:30pm GMT6+</p>
<form class="form-inline">
<input type="text" class="form-control" id="reply" placeholder="Type and enter to reply">
<button type="button" class="btn btn-default" id="repost">Re-Tweet</button>
</form>
</div>
When the button with the id #repost is clicked, i want to access the html inside the p tag with the id #text. I tried something like this:
$('#retweet').click(function(e){
e.stopPropagation();
var text = $(this).parent("div").closest('#text');
alert("some retweet button has been pressed which has the text:"+text);
});
You can use the jQuery .closest() function to get the containing <div> and then find the <p> tag you want inside it:
$('#repost').on('click', function () {
var text = $(this).closest('div[class^=col]').find('#text').html();
console.log(text);
});
The div[class^=col] selector means "find the closest div tag with a class starting with col". This allows you to use the other bootstrap column classes as well and have it still work.
$('#repost').click(function(){
console.log($(this).closest('div').find('#text').html());
});
See demo http://jsbin.com/wojupoyosa/1/edit?html,js,console,output
and as comments suggest you IDs should be unique per page so you should use a class or something else instead.
$( "#text" ).text() will give you the value inside P tag. So your code will look something like:
$('#repost').click(function(){
$( "#text" ).text() // save it to wherever you want
});
As a side note it is generally frowned upon to have css id's that are not unique - shared identifiers should use a class.
If you change all your ids into classes as shown in the demo below, then the following code should work fine. Also, you do not need the form element.
$('.repost').click(function(){
var text = $(this).closest('div').find('.text').text();
alert("some retweet button has been pressed which has the text: " + text);
});
$(function() {
$('.repost').click(function(){
var text = $(this).closest('div').find('.text').text();
alert("some retweet button has been pressed which has the text: " + text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-sm-5 narrow">
<p class="title">Jhon123</p>
<p class="text">This is the status of jhon</p>
<p>posted at 12:30pm GMT6+</p>
<form class="form-inline">
<input type="text" class="form-control reply" placeholder="Type and enter to reply">
<button type="button" class="btn btn-default repost">Re-Tweet</button>
</form>
</div>
<div class="col-sm-5 narrow">
<p class="title">Mary123</p>
<p class="text">This is the status of mary</p>
<p>posted at 12:35pm GMT6+</p>
<form class="form-inline">
<input type="text" class="form-control reply" placeholder="Type and enter to reply">
<button type="button" class="btn btn-default repost">Re-Tweet</button>
</form>
</div>