This question already has answers here:
Changing button text onclick
(19 answers)
Closed 4 years ago.
I have a function which returns bootstrap row and every row contains input field, textarea and remove button.
So I have multiple bootstrap rows as I am calling function for various time. After clicking on remove button I am changing border color of input and textarea just to indicate that I am not taking it into consideration. I have made remove button to work as toggle button so that it will add and remove error class that I am assigning to input and textarea.
Now I want to change the value of 'Remove' button to 'Add'. So that when I click on 'Add' button it will remove the style of input and textarea and it means that I can take those values into consideration.
function GetDynamicTextBox(value, tag) {
return'<div class="col-lg-4"><input class="form-control" type="text" value="'+tag+'" name="typetag" id="tags" data-role="tagsinput"/></div>'+'' +
'<div class="col-lg-6"><textarea class="form-control issuetext" name="comment" id="" cols="" rows="">'+value+'</textarea></div>'+
'<div class="col-lg-2">'+
'<input type="button" value="Remove" class="remove btn btn-default" /></div>'
}
$("body").on("click", ".remove", function () {
$(this).closest('#issue').find('.bootstrap-tagsinput').toggleClass('error')
$(this).closest('#issue').find('.issuetext').toggleClass('error')
});
<div class='row'id="issue">
<div class="col-lg-4">
<input class="form-control" type="text" value="'+tag+'" name="typetag"
id="tags" data-role="tagsinput"/></div>
<div class="col-lg-6">
<textarea class="form-control issuetext" name="comment" id="" cols=""
rows="">'+value+'</textarea></div>
<div class="col-lg-2">
<input type="button" value="Remove" class="remove btn btn-default" /></div>
</div>
It's pretty straightforward. Just add a click event to the button. The click event will give you an event (e) and you can then call the standard .innerText property on the element to set it. No need for jQuery here...
const btn = document.getElementById('testButton');
let clickCount = 0;
btn.addEventListener('click', (e) => {
e.currentTarget.innerText += clickCount++;
});
<button type="text" id="testButton">Initial Value</button>
You can add an event listener to the button and change its textContent according to the value of a global variable.
<button id="removeOrAdd">Remove</button>
<script>
var remove = true;
document.getElementById("removeOrAdd").addEventListener("click", function(e){
if(remove){
this.textContent = "Add";
remove = false;
} else {
this.textContent = "Remove";
remove = true;
}
});
</script>
Related
I have the following HTML :
<button type="button" id="Button">Go</button>
<div id="validation"></div>
I'm trying to add event handlers to dynamically generated elements in the following way :
Click button -> Generate element X inside div #validation -> Attach event handler to element X
$(document).ready(function(){
ID = 1;
$("#Button").click(function(){
/*generate new div inside div #validation with id #validationID
1st one would be #validation1
it contains a form with name accepterID and a button with name refuserID
1st ones would be accepter1 and refuser1*/
var newline = `
<div id="validation${ID}">
<form name="accepter${ID}">
<input type="hidden" name="name" value="phoegasus">
<button type="submit" value="valider">
</form>
<button name="refuser${ID}">refuser</button>
</div>
`
$("#validation").append(newline);
/*attach event handlers to the generated elements
1st iteration would attach handlers to accepter1 and refuser1 */
$("#validation").on('submit',"form[name^='accepter"+ID+"']",function(e){
$("#validation" + ID).remove();
//remove div validationID after submitting form
});
$("#validation").on('click',"button[name^='refuser"+ID+"']",function(){
$("#validation" + ID).remove();
//remove div validationID
});
ID++;
});
});
When I submit the form or I click the generated button I want to remove the div that contains them. If I press the button refuser1, it should delete the div #validation1.
When the elements are generated the handlers aren't attached to them.
The code doesn't work when it's executed during the onclick event but when I execute it in the navigator console it works.
I tried using DOMSubtreeModified on the div with id #validation, but it didn't work.
you can manage it by using a class (or another element) in second argument of your on function.
For that, DO NOT declare your event listeners inside your add event.
This is a full working example :
$("#validation").on('submit',"form.validation-form",function(e){
e.preventDefault();
console.log('form', $(this).attr('data-id'), ' submitted');
});
$("#validation").on('click',"button.validation-refuser",function(){
console.log('clicked on refuser for form ', $(this).attr('data-value'));
//code
});
var ID = 1;
$('#my-adder').on('click', function () {
$('#validation').append('<form name="accepter'+ID+'" class="validation-form" data-id="'+ID+'"><input type="text" placeholder="my text field" /><button class="validation-refuser" name="refuser'+ID+'" data-value="'+ID+'">Refuser button</button><button type="submit">SUBMIT</button></form>');
ID++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="validation">
<form name="accepter0" class="validation-form" data-id="0">
<input type="text" placeholder="my text field" />
<button type="button" class="validation-refuser" name="refuser0" data-value="0">Refuser button</button>
<button type="submit">SUBMIT</button>
</form>
</div>
<button id="my-adder">ADD A FORM</button>
Hope it helps
I have an input field and a button next to it, what i want to do is whatever i type in the input field then click on the button next to it, the result gets displayed in another button, here is what i tried so far:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
document.getElementById("btnresult").value = result;
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
https://jsfiddle.net/sheriffderek/p2LoLcv3/
I think this is what you are describing...
Some simplified markup
<div class="parent">
<input type='button' value='Add' rel='action' /><br>
<input type='text' rel='text-input' />
</div>
<ul class='button-list' rel='button-list'>
<!-- you need to put the buttons somewhere, right? -->
</ul>
jQuery was one of the tags, so I used it
// just caching some thing that will be reused (I like using rel)
var $parent = $('.parent'); // whatever - to keep some scope
var $addButton = $parent.find('[rel="action"]');
var $textInput = $parent.find('[rel="text-input"]');
var $buttonList = $('[rel="button-list"]');
$addButton.on('click', function() { // on click...
var currentInputValue = $textInput.val(); // get the value from input...
$buttonList.append('<li><button>' + currentInputValue + '</button></li>'); // append a new button...
$textInput.val(''); // clear input
});
You're almost there, you have to unhide the button you've hidden in the first place, and not set a value for a button, but rather the innerHTML property. Since a button doesn't hold a value, but displays the content between the tags as text.
I've commented my changes:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
// Changed from .value to .innerHTML
document.getElementById("btnresult").innerHTML = result;
// Changed style from to 'block'
document.getElementById("btnresult").style.display = "block"
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
In addition, there are several aspects of your code that could use improvement, I described them below:
function add_keyword() {
// No need for parentheses around the document.getElement function.
var keyword_value = document.getElementById("keyword").value;
// There's no need to place the value in a new variable, it is useful to place the element you wish to replace in a variable, since we'll be re-using it's instance.
var btn = document.getElementById("btnresult");
btn.innerHTML = keyword_value;
btn.style.display = "block"
}
EDIT: Since OP's goal was to create a new button with the content, this is an updated version that generates a new button for every new input.
function add_keyword() {
var keyword_value = document.getElementById("keyword").value;
// Create a new button element.
var btn = document.createElement("button");
// Set it's content to the keyword from the input.
btn.innerHTML = keyword_value
// Append it to the body.
document.body.appendChild(btn);
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
I'm building a multipage form. On a few of the form's pages, I have questions that allow the user to add inputs dynamically if they need to add a job, or an award, etcetera. Here's what I'd like to do/what I have done so far.
What I Want to Do:
As the user adds fields dynamically, I want to validate those fields to make sure they have been filled in, and they are not just trying to move to the next page of the form with empty inputs.
After all the fields are successfully validated, a "Next" button at the bottom of the page, which up until this point was disabled, will become reenabled.
What I know How To Do
With some help, I've been able to workout a validation pattern for the inputs that are not dynamically added (such as First Name, Last Name) and I can extend this same logic to the first set of inputs that are not added dynamically. I have also worked out how to re-enable the "Next" button once all fields are good.
What I do Not Know How To Do
How do I write a function that extends the logic of the simple validation test to also check for dynamically added iterations.
http://codepen.io/theodore_steiner/pen/gwKAQX
var i = 0;
function addJob()
{
//if(i <= 1)
//{
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'"> <input type="date" class="three-lines" name="years_'+i+'"> <input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
//}
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
function checkPage2()
{
var schoolBoard_1 = document.getElementById("schoolBoard_1").value;
if(!schoolBoard_1.match(/^[a-zA-Z]*$/))
{
console.log("something is wrong");
}
else
{
console.log("Working");
}
};
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<p class="subtitleDirection">Please list in chronological order, beginning with your most recent, any and all full-time or part-time teaching positions you have held.</p>
<div class="clearFix"></div>
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" id="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='School Board'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
<input type="date" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
</div><!--end of previousTeachingExperience Div -->
Instead of trying to validate each individual input element, I would recommend trying to validate them all at once. I believe that is what your checkPage2 function is doing.
You can add the onBlur event handler or the onKeyUp event handler you are currently using to all added inputs to run your form wide validation. This has the effect of checking each individual form element if it is valid so you know for sure you can enable the submit button.
Lastly, when removeJob is called, you should also run the form wide validation. It would look something like this:
function addJob()
{
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'" onkeyup="checkPage2()"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'" onkeyup="checkPage2()"> <input type="date" class="three-lines" name="years_'+i+'" onkeyup="checkPage2()"> <input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
checkPage2();
};
For every element that you make with document.createElement(...), you can bind to the onchange event of the input element, and then perform your validation.
Here's an updated version of your CodePen.
For example:
HTML
<div id="container">
</div>
Javascript
var container = document.getElementById("container");
var inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.onchange = function(e){
console.log("Do validation!");
};
container.appendChild(inputElement);
In this case I'm directly creating the input element so I have access to its onchange property, but you can easily also create a wrapping div and append the inputElement to that.
Note: Depending on the freqency in which you want the validation to fire, you could bind to the keyup event instead, which fires every time the user releases a key while typing in the box, IE:
inputElement.addEventListener("keyup", function(e){
console.log("Do validation!");
});
This is what I have right now. I'm trying to add fields to the form dynamically using jQuery add() and append() method. But I want to remove the particular added field when the remove button is clicked.
<div class="col-md-12">
<h3>Added Description Fields</h3>
<div class="col-md-12" id="descFields">
</div>
</div>
JS
$(document).ready(function() {
console.log(descFields);
$('#addDesc').click(function(e) {
var descFields = $('#descFields');
var descLabel = $('#descLabel').val();
var large = '<div class="form-group" id="descField"><div class="input-group"><input type="text" class="form-control" placeholder="Enter Value For ' + descLabel + '" /><span class="input-group-btn"><button class="btn btn-danger" id="removeDesc" type="button">Remove</button></span></div>';
descFields.add(large).appendTo(descFields);
e.preventDefault();
});
$('#removeDesc').click(function(e) {
$(this).remove();
});
});
When the user click on the #removeDesc button , the the field that is added should be removed. I cannot figure out how to achieve this.
There are many ways of doing this, but the simpler for your problem is this one:
$(document).ready(function() {
console.log(descFields);
$('#addDesc').click(function(e) {
var descFields = $('#descFields');
var descLabel = $('#descLabel').val();
var large = '<div class="form-group" id="descField"><div class="input-group"><input type="text" class="form-control" placeholder="Enter Value For ' + descLabel + '" /><span class="input-group-btn"><button class="btn btn-danger" id="removeDesc" type="button">Remove</button></span></div>';
descFields.add(large).appendTo(descFields);
e.preventDefault();
});
$('#descFields').on('click', '#removeDesc', function(e) {
$(this).parents('.form-group').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="descLabel"/>
<button id="addDesc">Add Desc</button>
<div class="col-md-12">
<h3>Added Description Fields</h3>
<div class="col-md-12" id="descFields">
</div>
</div>
Your problem is in the callback to delete the rows. When the document has finished loading you are trying to attach a click event to an object #removeDesc that is still not present in the DOM because it's created on the fly when the user clicks the #addDesc.
That's why you should use:
$('#descFields').on('click', '#removeDesc', function(e) {
$(this).parents('.form-group').remove();
});
As #vijayP suggested before you can use the on() to attach an event handler to the container where you'll be adding the object that is still not present in the DOM. Then you pass in the query selector as the second parameter to filter in execution time which of its children will trigger the event and execute the callback.
My additional trick is that I'm using .parents('.form-group') to select the div containing the group and remove all of the fields that were added instead of removing only the button.
Happy coding!
Add click event for remove button like follows:
$(document).on("click","#removeDesc",function(e) {
$(this).remove();
});
HTML :
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="button" class="mybutton" value="focus next" onclick="focusNext()">
<input type="button" class="mybutton" value="focus prev" onclick="focusPrev()">
JS code :
//focused is getting last focused textfield
var focused = null;
$(".mytextbox").focus(function(){
focused = $(this);
});
//focus next
function focusNext(){
$(".mytextbox").each(
//checking is this textbox focused
if($(this)[0] == focused[0]){
$(this).next().focus();
//or
$(this).next(".mytextbox").focus();
}
);
}
//focus prev
function focusPrev(){
$(".mytextbox").each(
//checking is this textbox focused
if($(this)[0] == focused[0]){
$(this).prev().focus();
//or
$(this).prev(".mytextbox").focus();
}
);
}
i think $(this).next() is not working.. is next() function not working in each ???
how can i focus next or previous text field when button clicked?
Help me.. and thank you..
In your script you have synatx errors as .each() should have a function as its param.
Apart from that there is a logical error in the each loop, since you are calling focus() in the loop the focus handler will get called and will chage the variable referred by focus so the next iteration also will be true so the Next button will not work.
var focused = null;
$(".mytextbox").focus(function () {
focused = $(this);
});
//focus next
function focusNext() {
if (focused && focused.length) {
focused.next('.mytextbox').focus();
}
}
//focus prev
function focusPrev() {
if (focused && focused.length) {
focused.prev('.mytextbox').focus();
}
}
Demo: Fiddle
Assuming that first input field is focused by default when page loads, please see below code -
HTML : put ids for button to bind click event
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input id="nextBtn" type="button" class="mybutton" value="focus next">
<input id="prevBtn" type="button" class="mybutton" value="focus prev">
jQuery : set focus for first field. Check if next or prev element is present when click on next or previous button and then set focus accordingly.
$(function(){
//focus first input fields
$(".mytextbox:first").focus();
var currentFocusedInput = $(".mytextbox:first");
// next button
$("#nextBtn").click(function(){
var nextInputToFocus = currentFocusedInput.next('.mytextbox');
if($(nextInputToFocus).length > 0)
{
currentFocusedInput = $(nextInputToFocus);
}
$(currentFocusedInput).focus();
});
// previous button
$("#prevBtn").click(function(){
var prevInputToFocus = currentFocusedInput.prev('.mytextbox');
if($(prevInputToFocus).length > 0)
{
currentFocusedInput = $(prevInputToFocus);
}
$(currentFocusedInput).focus();
});
});
JSFiddle Demo