If element doesn't exist, add to input field in javascript - javascript

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.

Related

<pattern> & required doesn't work on dynamically created form

I'm trying to implement client-side input validation for a datatables-editor that I'm rewriting. The form is created dynamically and then added to a bootstrap-modal.
I have encountered a problem where adding <pattern> and/or required doesn't result in any added functionality at all. The form just accepts the input and submits, and I'm quite confused as to why that is.
EDIT:
I have added the relevant code to a plunkr
I have now added the full project. Specifically the issue is connected to the _openEditModal function and _openAddModal function, where i generate the forms dynamically and add the pattern='patternVariable'.
The pattern for this example (however it doesn't work no matter what pattern I use):
^[a-zA-Z0-9\.]+$
Creating the form:
var data = "";
data += "<form name='altEditor-form' role='form'>";
for(var j = 0; j < columnDefs.length; j++){
data += "<div class='form-group'><div class='col-sm-3 col-md-3 col-lg-3 text-right' style='padding-top:7px;'><label for='" + columnDefs[j].title + "'>" + columnDefs[j].title + ":</label></div><div class='col-sm-9 col-md-9 col-lg-9'>";
if(columnTypes[j].type.includes("text")){
data += "<input type='" + columnTypes[j].type + "' id='" + columnDefs[j].title + "' pattern='" + columnPattern[j].pattern + "' title='" + patternErrMsg[j].msg + "' required name='" + columnDefs[j].title + "' placeholder='" + columnDefs[j].title + "' style='overflow:hidden' class='form-control form-control-sm' value='" + adata.data()[0][newaData[j].name] + "'>";
}
if(...){...}
data +="</div><div style='clear:both;'></div></div>";
}
data += "</form>";
As you can see I add the tags like so:
pattern='" + columnPattern[j].pattern + "' title='" + patternErrMsg[j].msg + "' required ...
The modal:
$('#altEditor-modal').on('show.bs.modal', function() {
$('#altEditor-modal').find('.modal-title').html('Edit Record');
$('#altEditor-modal').find('.modal-body').html(data);
$('#altEditor-modal').find('.modal-footer').html("<button type='button' data-content='remove' class='btn btn-default' data-dismiss='modal'>Close</button>\
<input type='submit' data-content='remove' class='btn btn-primary' id='editRowBtn'>Save Changes</input>");
I made sure that the button has type='submit' as I've read that this is what triggers the pattern-check.
editRowBtn code:
$(document).on('click', '#editRowBtn', function(e)
{
e.preventDefault();
e.stopPropagation();
that._editRowData();
});
To make sure that my code is actually adding the attributes to the input i checked the console:
Any help or advice is greatly appreciated as I'm kinda stuck here.
It's a little hard to read your examples (a plunkr would be nice :) ), but from what I can see, you've put your submit button outside your form.
That won't work, since the button won't know what it's submitting.
Try putting the submit button inside the form.
Alternatively, try using the form attribute on the submit button, which should reference the form ID. I've never used this myself, but according to MDN, it's part of the HTML5 spec.
Form attribute description from MDN:
The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a element in the same document. If this attribute is not specified, this element must be a descendant of a element. This attribute enables you to place elements anywhere within a document, not just as descendants of their form elements. An input can only be associated with one form.

How can I retrieve input values from elements added after page load?

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)

Edit dynamically created row in a form

I have difficulties to edit in form dynamically added rows. For example if some of the cell in the row have error - clicking on it will feed the form with selected row. Hope I'm clear.
Here is a code:
(document).ready(function(){
$("#inputtitle").append("<input type='text' name='type1' placeholder='Title'/><br>");
$("#inputremarks").append("<input type='text' name='type2' placeholder='Remarks'/><br>");
$("#inputdate").append("<input type='text' name='type3' placeholder='Date'/><br>");
$("#inputoption").append("<input type='text' name='type4' placeholder='Option'/><br>");
});
$("form").submit(function(e){
e.preventDefault();
var newName = $('form').find('input[name="type1"]').val();
var newName1 = $('form').find('input[name="type2"]').val();
var newName2 = $('form').find('input[name="type3"]').val();
var newName3 = $('form').find('input[name="type4"]').val();
$('table').append('<tr><td>' + newName + '</td><td>' + newName1 + '</td><td>' + newName2 + '</td><td>' + newName3 + '</td></tr>' );
});
Sorry for being not clear. My question was how to feed back the form when click to one of the new created row. Below is updated JSFiddle with approximate solution, but not correct, because probably need another button with name UPDATE and may be need another column with ID. DEMO.
I desided to go by different way. So I created additional button to run a script for editing cell of created table. The link to the code you can find [here] Using jQuery to edit individual table cells

Removing checkboxes dynamically added to a div

I am using the following code to dynamically create a set of checkboxes based on user input from dropdown list. It does not delete the previous selections when the user select another option from the dropdown list.
It only deletes the checkboxes but not the description attached to the check box. I am unable to find the error with the code. Appreciate your help.
$(document).ready(function() {
$('#sel_LearnA').change(function(event) {
var $learnA=$("select#sel_LearnA").val();
$.get('actionDataSelect',{LAreaID:$learnA},function(responseJson) {
// remove existing checkboxes
$('#somediv').children().remove();
// add checkboxes to the div
$.each(responseJson, function(index, item) { // Iterate over the JSON array.
$('#somediv').append("<input type='checkbox' value='"+ item.keyCode + "' />" + item.keyCode + "</br>");
});
});
});
});
And my jsp looks like,
<div id="somediv"></div>
.children() gets only the element nodes of the parent, not the text nodes
Try empty()
$('#somediv').empty();
or just .html('')
$('#somediv').html('');
Empty function resets div.
$( "#yourDivId" ).empty();
This is not the error in your code.
The description is not attached to the checkbox.
$('#somediv').append("<input type='checkbox' value='"+ item.keyCode + "' />" + item.keyCode + "</br>");
You are closing the checkbox and the description is given after. So .remove will remove the checkbox, not the description.
Put the checkbox and description inside a label and remove the label.
This will definitely work.
$('#somediv').append("<label><input type='checkbox' value='"+ item.keyCode + "' />" + item.keyCode + "</label></br>");

How to create additional fields and remove them from a form?

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.

Categories

Resources