I am trying to allow users to add additional email fields if they want to add additional email accounts, and hit remove if they hit they do not want to add the field. However, I cannot get the remove button to work, and I was also, trying to somehow differentiate each class by including a variable emailCount in each class but that is not working either for some reason...
Here is the jquery script: (it is in a document ready function)
var i = 0;
$(function(){
i =+ 1;
var emailCount = "Email" + i.toString();
console.log(i);
console.log(emailCount);
$('.addEmail').click(function() {
$('#addInfo').append('<div class="' + emailCount '"></div><form class="newEmail", method="post", action="newEmailPost"> <label>' + emailCount + '</label>' + '<input name="' + emailCount + '", type="email", value=""/><br><input type="submit", class="addNewEmail", value="Save Email"></input><button class="removeEmailField">Remove</button></form><br>');
});
$('.removeEmailField').click(function() {
$(emailCount).remove();
});
});
Here is the jade file: (it works correctly, but maybe it will help for visual purposes)
extends layout
block content
div.centerContent
div
form.validateForm(method="POST", action="/editUserProfile")
legend Edit Profile
input(type="text", name="firstName", maxlength="20", placeholder=ufirstName, value=ufirstName)
br
input(type="text", name="lastName", maxlength="20", placeholder=ulastName, value=ulastName)
br
input(type="email", name="email", maxlength="20", placeholder=uemail, value=uemail)
br
- if(uemailList.length > 0)
for userC in uemailListCount
for userE in uemailList
input(type="email", name=userC, maxlength="20", placeholder=userE, value=userE)
br
input(type="number", name="phone", maxlength="20", placeholder=uphone, value=uphone)
br
input(type="date", name="birthday", value=ubirthday)
br
input.btn.btn-primary(type="submit", name="Update", value="Save")
a(href="/userProfile")
button.btn(type="button") Cancel
hr
div#addInfo
label Add another email address:
button.addEmail Add Email
br
label Add another phone number:
button.addPhone Add Phone Number
You can try this:
$("."+emailCount).remove();
i--;
If you want to add or remove several times make sure the emailCount is set with the right value, when adding you're not setting it again and when removing you're not changing i as well.
I think you might need to convert emailcount to a class format in the remove function. Something like:
var classifiedEmailCount = "." + emailCount;
$(stringifiedEmailCount).remove();
i--;
Ok I just changed it around a bit like this:
$('.addEmail').click(function() {
$('#addInfo').replaceWith('<div class="newEmailAdd"></div><form class="newEmail", method="post", action="/newEmailPost"> <label> Add Another Email </label>' + '<input name="emailNew", type="email", value=""/><br><input type="submit", class="addNewEmail", value="Save Email"></input><button class="removeEmailField">Remove</button></form><br>');
});
$('.removeEmailField').click(function() {
alert('You clicked remove');
$('.newEmailAdd').remove();
});
I did not need the multiple fields to work anymore.
Related
what I want is to make an input field appear on some kind of popup where the user can input a number between 0-x where x is the current level of a variable. Once the user inputs a number, that number gets added to a different variable. This would be much like transferring money in a videogame. I don't have any code for this but it would be awesome if you could help.
This may help you get started. I created a clickable label that opens a popover with an input field and a button for submission.
I'm using jQuery and Bootstrap.
JSFiddle: https://jsfiddle.net/Ravvy/xjz6ok62/
HTML:
<label>Money: $</label>
<label data-toggle="popover" title="Add Money" data-placement="bottom" id="moneyLabel">0.00</label>
JavaScript:
$(document).ready(function() {
var content = '<input id="moneyInput"></input>' +
'<button id="moneyButton" ' +
'onclick="addMoney()">Add</button>';
$('#moneyLabel').popover({content: content, html: true});
});
function addMoney() {
var currentAmount = parseFloat($('#moneyLabel').text());
var addedAmount = parseFloat($('#moneyInput').val());
var total = currentAmount + addedAmount;
$('#moneyLabel').text(total);
}
I am trying to add a hashtag to an input field. The problem is that when I add it, I can keep adding it. I am wondering of a way to check the input field and if the hashtag already exists, to not add it?
My javascript is:
$('.item').click(function(){
var clonedTag = $("<div class='tag_clone' data-value=" + ($(this).attr('data-value')) + ">"+($(this).attr('data-value')) + "<a href='javascript:void(0)' class='remove' tabindex='-1' title='Remove'>" + "×" + "</a>" + "</div>")
$('.selectize-input.items.not-full').append(clonedTag)
})
$('.selectize-input.items.not-full').on('click', '.remove', function(e){
$(this).parent('.tag_clone').remove()
e.preventDefault();
})
So, if #example1 exists in the top input field, a user can not add it again (I'm using Selectize.js)
In the image below, I click the bottom input field to get a clone of the hashtag to the top input field.
Alright, So basically I got a website that recieves a number of inputs, like lets say name, age, weight...
After all the inputs, the text appears in a text area on the same website.
I need the website to offer the function to add more levels,
for example you click 'add level' and a dynamic new inputs appear that allow you to add more info.
Im facing a problem that when i create a new dynamic div with those inputs, they all have the same id, which wont allow me to print each one individually.
I have this function that prints out the results :
<form id="form" action="#">
<script>
$("#form").submit(function(event) {
event.preventDefault();
$("#template").val()...
</form>
Shortly : I need a way to make a button, that adds a new div with unique id.Inside there will be label inputs, the label will print out on submit.
Hope this is clear enough :)
If I understand your question correctly, this might be a way to do it :
HTML
<button id="addLevelBtn">Add a level</button>
<button id="getResultsBtn">Get results</button>
JS
//on click, add a level
$('#addLevelBtn').on('click',addLevel);
//on click, get results
$('#getResultsBtn').on('click',getResults);
//add the first level on load
addLevel();
function addLevel(){
var nbOfSets = $('.setOfInputs').length;
$('#addLevelBtn').before(
'<div class="setOfInputs" id="set-'+nbOfSets+'">'
+'<p>#set-'+nbOfSets+'</p>'
+'<label for="age">Age: </label>'
+'<input type="text" name="age">'
+'<label for="weight">Weight: </label>'
+'<input type="text" name="weight">'
+'</div>');
}
function getResults(){
var result="";
$.each($('.setOfInputs'),function(){
var id = $(this).attr('id');
var age = $(this).find('[name=age]').val();
var weight = $(this).find('[name=weight]').val();
result += id + ' : age = ' + age + ' , weight = ' + weight + '\n';
});
alert(result);
}
JS Fiddle Demo
Although the question title gives an impression that I want to ask one question, but there are two problems I have facing at the moment.
I have gone through few similar questions on how to clear the input text area on button click, but most of them are for fixed input class or id's.
Problem 1: I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
Problem 2: After entering individual values in the betslip input boxes and if I click "clear all" button. It should clear all the inputs entered earlier in the bet slip.
Here is the HTML structure
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field - This is where I am creating the input fields
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text" class="betInput"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
HTML for Apply to all and Clear all button
APPLY TO ALL <input type="text">
CLEAR ALL
JS where I need to implement those 2 functions
function applyToAllBetInput() {
$('.apply').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
}
function clearAllBetInput() {
$('.clearall').click(function() {
$('div.bet').find('input').val('');
});
}
The best thing to do is remove the inline event handlers from the links, like this...
APPLY TO ALL <input type="text">
CLEAR ALL
Then, assign the event handlers in your script...
$("a.button.apply").on("click", function(e) {
e.preventDefault();
applyToAllBetInput($(this).find("input").val());
});
$("a.button.clearall").on("click", function(e) {
e.preventDefault();
applyToAllBetInput("");
});
And this would apply the value to all inputs...
function applyToAllBetInput(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}
If you pass a parameter into applyToAllBetInput and then set the inputs with that then you only need the one function, as they both do the same thing, but with different values. Best to only have 1 bit of code if it's only doing 1 thing, then you only have to fix it once if things change in the future :)
Please replace the id's i've given with your actual button/textarea ids (give ID's to your elements).
$('#txtApplyToAll').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
$('#btnClearAll').click(function() {
$('#txtApplyToAll').prevAll().find('input[type=text].val('');
});
There are several general suggestions I'd make before even starting to write the code. First, Why are you using longhand JavaScript when you have jQuery available? For example:
inputId = divId.document.getElementById('input');
should be simply:
inputId = $(inputId).find('input');
(or something along those lines--I'm not sure what you're after with that.)
Next, you're using inline click handlers. Instead, use event listeners:
<a href="javascript: applyToAllBetInput()" ...
Should be
$('a#my-id').click(function() { ... }
Finally, you can target all your inputs for clearing with a selector like this:
$('div.bet').find('input').val('');
I'm working with Zend Framework 1.12 and I've need to be able to dynamically add and delete fields from a sub-form, in this case we're associating hyperlinks to a parent "promotion".
I haven't found a way to accomplish dynamically adding and removing elements via Zend, and the rare tutorial I've found that claimed to do this are half a decade old and aren't working when I attempt them.
So what I am doing is storing the links I need to work with in a Zend Hidden input field and then dealing with the JSON data after I submit. Not very efficient, but it's the only thing I've gotten to work so far.
Below is the section of the code I'm working with:
Assume a form like:
<form action="/promos/edit/promo_id/15" method="POST" id="form_edit">
<!-- input is Zend_Form_Element_Hidden -->
<input type="hidden" id="link_array" value="{ contains the JSON string }"/>
<button id="add_link">Add Link</button>
</form>
The purpose is that every time the Add Link button is pressed, the form adds fields to allow the user to input new hyperlinks that will be associated with the specific items.
Here's the function:
// add links
$('#add_link').click(
function(e) {
e.preventDefault();
link = '<div class="p_link new_link">' +
'<div class="element_wrap">' +
'<label for="link_name" class="form_label optional">Text: </label>' +
'<input type="text" id="new_link_name" name="link_name"/>' +
'</div>' +
'<div class="element_wrap">' +
'<label for="link_http" class="form_label optional">http://</label>' +
'<input type="text" id="new_link_http" name="link_http"/>' +
'</div>' +
'<div class="element_wrap">' +
'<button class="submit delete_link">Delete</button>' +
'</div>' +
'</div>';
$('#add_link').prev().after(link);
}
);
Now, what I need to do is on submit, for every new_link class element, to take the links name and http reference and place it in a json object. Here's the code as I have it so far (I know I don't have both input fields represented at this point):
$('#submit').click(
function(e) {
e.preventDefault();
var link_array = [];
var new_links = document.getElementsByClassName('new_link');
$.each(new_links, function() {
console.log(this);
var n = $(this).children('#new_link_name').text();
console.log(n);
link_array.push({'link_name':n}); //'link_http':h
});
console.log(JSON.stringify(link_array));
}
);
My problem is that: var new_links = document.getElementsByClassName('new_link'); will collect all the newly added new_link elements, but it does not pull in any value that has been input into the text fields.
I need to know how I can apparently bind any input I make to the input field's value attribute, because right now anything I type into these new elements are tossed out and the field appears empty when it's anything but.
$('#submit').click(
function(e) {
e.preventDefault();
var link_array = [];
var new_links = $('.new_link');
$.each(new_links, function() {
console.log(this);
var n = $(this).find('input').val(); // you need input values! This line //is changed...
console.log(n);
link_array.push({'link_name':n}); //'link_http':h
});
console.log(JSON.stringify(link_array));
}
);
JSFIDDLE: http://jsfiddle.net/DZuLJ/
EDit: You can't have multiple IDS (make class for each input, and target class, if you want link names and http's)