Is there a way to add new fields with the same key, but independently of each other? I want both groups to be added using Enter.
Currently, fields with values are added with Enter, groups with Shift.
My actual code in form:
<div id="parent" class="list-group">
<div class="form-group form-filed horizontal">
<input name="values[]" class="input" type="text" autocomplete="off" placeholder="Enter value"
autofocus onkeypress='validate(event)' onkeydown="pressEnter(event)" required>
</div>
</div>
<div id="parent" class="list-group">
<div class="form-group form-filed horizontal">
<input name="groups[]" class="input" type="text" autocomplete="off" placeholder="Enter group"
autofocus onkeypress='validate(event)' onkeydown="pressEnter(event)" required>
</div>
</div>
Javascript:
function pressEnter(evt){
if(evt.which==13)
addDivValue();
if(evt.which==16)
addDivGroup();
}
function addDivValue(){
var newDiv = document.createElement("div");
newDiv.className= 'form-group form-filed horizontal';
var input=document.createElement("input");
input.placeholder='Enter value';
input.type='text';
input.className='input';
input.autocomplete='off';
input.name= 'values[]';
input.required=true;
input.addEventListener("keypress",validate);
input.addEventListener("keydown", pressEnter);
newDiv.appendChild(input);
var parentDiv = document.getElementById("parent");
parentDiv.appendChild(newDiv);
input.focus();
}
function addDivGroup(){
var newDiv = document.createElement("div");
newDiv.className= 'form-group form-filed horizontal';
var input=document.createElement("input");
input.placeholder='Enter group';
input.type='text';
input.className='input';
input.autocomplete='off';
input.name= 'groups[]';
input.required=true;
input.addEventListener("keypress",validate);
input.addEventListener("keydown", pressEnter);
newDiv.appendChild(input);
var parentDiv = document.getElementById("parent");
parentDiv.appendChild(newDiv);
input.focus();
}
Related
I have a form for which I should write validation logic.
Let's say there's an input field like this.
<div class="group1"><label>Product code</label> <input id="code" name=""code" type="text" class="control1"></div>
If I want to make it a required field how do I write the logic?
I don't have access to the CSS files. But there's an input like this which I can use which has a red outline.
<div class="group1 row has-error">
<div><input type="text" class="control1"></div>
</div>
I have to give the code in JavaScript or jQuery.
Get an element and set true on required property.
const input1 = document.getElementById('code');
input1.required = true;
const input2 = document.querySelector('div.group1>div>input.control1');
input2.required = true;
<form>
<div class="group1"><label>Product code</label>
<input id="code" name="code" type="text" class="control1">
</div>
<div class="group1 row has-error">
<div>
<input type="text" class="control1">
</div>
</div>
<input type="submit">
</form>
I think this is what you need
$("#formSubmit").submit(function(e) {
e.preventDefault();
var error_text = "<div class='text-danger error_val'>Cannot be empty</div>"
var data = $("#formSubmit").serializeArray();
var allInputs = $("#formSubmit input");
for(var i=0; i<data.length; i++){
if(data[i].value.length == 0){
$(".group1").addClass('has-error');
var errorDiv = $(allInputs)[i].closest('.has-error');
$(error_text).insertAfter( errorDiv );
}
}
});
.has-error input{
border: 1px solid #f00;
}
.text-danger{
color:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formSubmit">
<div class="group1 row">
<label>Product code</label>
<input id="code" name="code" type="text" class="control1" >
</div>
<button type="submit" id="submitButton">Save</button>
</form>
I know it`s too late but you can use these functions to make an input required/optional
function makeFieldRequired(element, elementName) {
let jqueryObj = $(element);
jqueryObj.attr('title', `${elementName} is required`);
jqueryObj.attr('required', 'true');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function makeFieldOptional(element) {
let jqueryObj = $(element);
jqueryObj.removeAttr('required');
jqueryObj.removeAttr('title');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function refreshFormValidtion(form) {
$(form).removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm trying to create an interactive resume template using javascript and html and have managed to use cloneNode to duplicate work history blocks (see attached screenshot)
The problem(s) I am having is that clicking on the add list item button in the cloned/duplicated work history block at the bottom, creates a <li> item in the 1st/cloned element.
The objective is to be able to add or delete ````` list elements within a specific work history block and to also be able to add/remove entire work history sections. Currently it deletes from the top down, which is also an issue.
Thanks for any pointers in advance.
CODE
<!DOCTYPE html>
<html>
<body>
<div id="test">
<div id="node">
<div class="work_history">
<div class="row">
<strong>
<input type="text" name="company" value="ACME Company">
</strong>
</div>
<div class="row">
<input type="text" name="position" value="Cheese Taster">
</div>
<input type="text" name="start" value="1/2019">
<input type="text" name="end" value="2/2020">
<ul id="list">
<li>
<textarea id="task" name="task" rows="4" cols="50">Did some things. Tasted cheese.</textarea>
</li>
<button onclick="addTask()">Add List Item</button>
<button onclick="RemoveTask()">Delete List Item</button>
</ul>
<button onclick="addWork()">Add Work</button>
<button onclick="removeWork()">Remove Work</button>
</div>
</div>
</div>
<script>
function addWork() {
var div = document.getElementById("node");
var cln = div.cloneNode(true);
//cln.setAttribute( 'id', 'newId');
document.getElementById("test").appendChild(cln);
}
function removeWork(){
var last = document.getElementById("test");
// want to delete the last added work history not first
last.removeChild(last.childNodes[0]);
}
function addTask(){
var ul = document.getElementById("list");
var task = document.getElementById("task");
var li = document.createElement("li");
li.setAttribute('id',task.value);
li.appendChild(document.createTextNode(task.value));
ul.appendChild(li);
}
function removeTask(){
var ul = document.getElementById("list");
var task = document.getElementById("task");
var item = document.getElementById(task.value);
ul.removeChild(item);
}
</script>
</body>
</html>
You'd have to use e.currentTarget instead of document.getElementById, otherwise you're only referring to the first instance of it:
function addWork(e) {
const div = e.currentTarget.parentElement;
const cln = div.cloneNode(true);
document.getElementById("test").appendChild(cln);
}
function removeWork(e) {
const last = e.currentTarget.parentElement;
last.parentElement.removeChild(last);
}
function addTask(e) {
const ul = e.currentTarget.parentNode;
let task = ul.children[0].childNodes[1].value;
let li = document.createElement("li");
// Replace paragraph breaks
task = task.replace(/\r?\n|\r/g, " ");
li.innerText = task;
ul.appendChild(li);
}
function removeTask(e) {
const ul = e.currentTarget.parentNode;
ul.removeChild(ul.lastChild);
}
<!DOCTYPE html>
<html>
<body>
<div id="test">
<div id="node">
<div class="work_history">
<div class="row">
<strong>
<input type="text" name="company" value="ACME Company">
</strong>
</div>
<div class="row">
<input type="text" name="position" value="Cheese Taster">
</div>
<input type="text" name="start" value="1/2019">
<input type="text" name="end" value="2/2020">
<ul id="list">
<li>
<textarea name="task" rows="4" cols="50">Did some things. Tasted cheese.</textarea>
</li>
<button onclick="addTask(event)">Add List Item</button>
<button onclick="removeTask(event)">Delete List Item</button>
</ul>
<button onclick="addWork(event)">Add Work</button>
<button onclick="removeWork(event)">Remove Work</button>
</div>
</div>
</div>
</body>
</html>
This allows you to refer to the specific element where the click event occurred and add/remove any elements that are relative within the DOM.
As a side note, it's best practice to have unique id attributes, adding the same id to multiple elements goes against that.
var add_button = $(".add_form_field");
var wrapper = $(".container1");
var max_fields = 9;
var x = 1;
$(add_button).click(function (e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append(
` <div class="email">
<label for="">Year</label>
<input type="text" name="eduYear${x}">
<label for="">Title Name</label>
<input type="text" name="eduTitle${x}">
<label for="">Institution/School Name</label>
<input type="text" name="eduPlace${x}">
<label for="">Details</label>
<input type="text" name="eduNotes${x}"> <br>Delete<hr></div>`
); //add input box
}
});
$(wrapper).on("click", ".delete", function (e) {
e.preventDefault();
$(this).parent("div").remove();
x--;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<h2>Educations</h2>
<button type="button" class="add_form_field">Add Education
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div class="email">
<label for="">Year</label>
<input type="number" name="eduYear1">
<label for="">Title Name</label>
<input type="text" name="eduTitle1">
<label for="">Institution/School Name</label>
<input type="text" name="eduPlace1">
<label for="">Details</label>
<input type="text" name="eduNotes1">
</div>
you can try this to create dynamic form
How can I get the value of a textarea after input but not in same div with jQuery? I tried to do the foreach and find methods. I need to get the value and assign to JS object.
<div id="txtall">
<div class="subdiv">
<input type = "text" value = "firstInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea"> firsttextareavalue </textarea>
<div class="subdiv">
<input type = "text" value = "secondInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea" /></textarea>
<div class="subdiv">
<input type = "text" value = "thirdInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea" />second may be empty</textarea>
<div class="subdiv">
<input type = "text" value = "forthInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea" />last text area value</textarea>
When I click a button I need to get value.
$('#txtall').find('.subinput').each(function() {
console.log(this.value);
console.log($(".subtextarea",this).val());
});
The output needs to be:
firstInput
firsttextareavalue
secondInput
(this should be empty)
thirdInput
second may be empty
forthInput
last text area value
I also have to assign value to JS object.
function newObject(input,textarea)
{
this.input = input;
this.textarea = textarea;
}
var list = [];
$('#txtall').find('.subinput').each(function() {
var obj_1 = new newObject();
obj_1.input = this.value;
obj_1.textarea = $(".subtextarea",this).val();
list.push(obj_1);
});
By the way, I need to use this and I can't assign a different id or class to each input or textarea.
The textarea comes after the input, so it's the next() element from the parent .subdiv
$('#txtall').find('.subinput').each(function() {
console.log( this.value );
console.log( $(this).closest('.subdiv').next('.subtextarea').val() );
});
When you do $(".subtextarea",this) it's the same as $(this).find(".subtextarea"), which will only find descendants, and inputs don't have descendants.
Note that your HTML is invalid, you can only have the class attribute once, and you shouldn't be closing the textareas twice
There's also no reason to create instances here, and you can just map the elements
var list = $('#txtall').find('.subinput').map(function() {
return {
input : this.value,
textarea : $(this).closest('.subdiv').next('.subTextarea').val()
}
}).get();
console.log(list)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="txtall">
<div class="subdiv">
<input type="text" value="firstInput" class="subinput">
</div>
<textarea class="textarea subTextarea"> firsttextareavalue </textarea>
<div class="subdiv">
<input type="text" value="secondInput" class="subinput">
</div>
<textarea class="textarea subTextarea"></textarea>
<div class="subdiv">
<input type="text" value="thirdInput" class="subinput">
</div>
<textarea class="textarea subTextarea">second may be empty</textarea>
<div class="subdiv">
<input type="text" value="forthInput" class="subinput">
</div>
<textarea class="textarea subTextarea">last text area value</textarea>
</div>
Use .next() to get to the next element after the parent DIV.
function newObject(input, textarea) {
this.input = input;
this.textarea = textarea;
}
$("#button").click(function() {
var list = [];
$('#txtall').find('.subinput').each(function() {
var input = this.value;
var textarea = $(this).closest(".subdiv").next(".subTextarea").val();
var obj_1 = new newObject(input, textarea);
list.push(obj_1);
});
console.log(list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="txtall">
<div class="subdiv">
<input type="text" value="firstInput" class="subinput">
</div>
<textarea class="subTextarea"> firsttextareavalue </textarea>
<div class="subdiv">
<input type="text" value="secondInput" class="subinput">
</div>
<textarea class="subTextarea" /></textarea>
<div class="subdiv">
<input type="text" value="thirdInput" class="subinput">
</div>
<textarea class="subTextarea" />second may be empty</textarea>
<div class="subdiv">
<input type="text" value="forthInput" class="subinput">
</div>
<textarea \class="subTextarea" />last text area value</textarea>
</div>
<button id="button">Click me</button>
$('#txtall').find('.subinput').each(function() {
console.log( this.value );
console.log( $(this).closest('.subdiv').next('textarea').val() );
});
Try this Code use $(this).parent().next().val(); it will get the textarea next to the parent of input.
function newObject(input,textarea)
{
this.input = input;
this.textarea = textarea;
}
var list = [];
$('#txtall').find('.subinput').each(function() {
var obj_1 = new newObject();
obj_1.input = this.value;
obj_1.textarea = $(this).parent().next().val();
list.push(obj_1);
});
Working Fiddle
I've the problem with div id in script. I just want to know how to control div id for using function id in another script. Here's my form:
<div class="container">
<div class="row">
<div class="col-md-7 field_wrapper">
<div data-role="dynamic-fields">
<div class="form-inline">
<div class="form-group" id="txtboxToFilter">
<label for="nip">NIP:</label>
<input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/>
</div>
<div class="form-group">
<i class='fa fa-fw fa-plus'></i>
</div>
<span id="name_status"></span>
</div>
</div>
</div>
</div>
And here's my script:
$(document).ready(function(){
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="nip">NIP:</label> <input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/></div><div class="form-group"><label for="jabatan">Jabatan:</label><select class="form-control" id="jabatan" name="jeniskejadian" required><option value=""></option><option value="SMC / KAKANSAR">SMC / KAKANSAR</option><option value="STAFF OPERASI / KASIOPS">STAFF OPERASI / KASIOPS</option><option value="OSC / KORPOS">OSC / KORPOS</option><option value="DANTIM">DANTIM</option><option value="RESCUER">RESCUER</option><option value="STAFF KOMUNIKASI">STAFF KOMUNIKASI</option><option value="HUMAS">HUMAS</option><option value="STAFF ADMINLOG">STAFF ADMINLOG</option></select></div><div class="form-group"><i class="fa fa-fw fa-minus"></i></div><span id="name_status"></span></div></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
function checkname()
{
var name=document.getElementById( "UserName" ).value;
if(name)
{
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
user_name:name,
},
success: function (response) {
$( '#name_status' ).html(response);
if(response=="OK")
{
return true;
}
else
{
return false;
}
}
});
}
else
{
$( '#name_status' ).html("");
return false;
}
}
For the first time in
<div class="form-group" id="txtboxToFilter">
<label for="nip">NIP:</label>
<input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/>
</div>
It can be used to using function checkname(), but if I would to click in
<div class="form-group">
<i class='fa fa-fw fa-plus'></i>
</div>
for adding the same input type text with function of my script $(addButton)
var fieldHTML = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="nip">NIP:</label> <input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/></div><div class="form-group"><i class="fa fa-fw fa-minus"></i></div><span id="name_status"></span></div></div>';
but the result is that var fieldHTML couldn't use function onkeyup checkname(). Please help me...
You should pass a reference of the element on which the inline event listener is attached to. You need to pass the this reference to the function and use the this reference to get the element.
Change you functions by adding this.
e.g.
<input type="text" class="form-control" id="UserName" onkeyup="checkname(this);" placeholder="Masukkan NIP" required/>
Also, for fieldHTML
var fieldHTML = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="nip">NIP:</label>
<input type="text" class="form-control" id="UserName" onkeyup="checkname(this);" placeholder="Masukkan NIP" required/></div><div class="form-group"><label for="jabatan">Jabatan:</label><select class="form-control" id="jabatan" name="jeniskejadian" required><option value=""></option><option value="SMC / KAKANSAR">SMC / KAKANSAR</option><option value="STAFF OPERASI / KASIOPS">STAFF OPERASI / KASIOPS</option><option value="OSC / KORPOS">OSC / KORPOS</option><option value="DANTIM">DANTIM</option><option value="RESCUER">RESCUER</option><option value="STAFF KOMUNIKASI">STAFF KOMUNIKASI</option><option value="HUMAS">HUMAS</option><option value="STAFF ADMINLOG">STAFF ADMINLOG</option></select></div><div class="form-group"><i class="fa fa-fw fa-minus"></i></div><span id="name_status"></span></div></div>';
Function checkname(element) as :
variable element contains the element this is being used. You can access the element by using element variable.
function checkname(element)
{
var name= element.value;
console.log('Checkname '+name);
}
I created dynamic adding fields to form but I have problem with color input:
Standard inputs are added normally but input with color on first click is not adding and on next click 'Add field' is adding next fields with color to all inputs/.
Here is my code:
HTML:
<div class="form-group" id="propositionsFields">
<label class="col-md-4 control-label">Options</label>
<div class="row">
<div class="col-8">
<input class="form-control propositionField" name="proposition[]" type="text" />
</div>
<div class="col-2">
<input type="text" class="form-control jscolor {onFineChange:'updateColor(this)'}" />
<input type="hidden" class="color-picker" value="" />
</div>
<div class="col-2">
<button class="add-proposition-field propositionManage">Add field</button>
</div>
</div>
</div>
JS:
$(document).ready(function() {
var addField = $(".add-proposition-field");
var removeField = $('.remove-proposition-field');
addField.click(function(e) {
var rodzic = $('.colorInput');
e.preventDefault();
var i = $('.propositionField').size();
var color = 'FF0000';
var input = document.createElement("input");
input.className = "form-control";
input.setAttribute("value", color);
input.setAttribute("type", 'text');
var picker = new jscolor(input);
var newField = '<div class="row"><div class="col-8"><input autocomplete="off" class="form-control" name="proposition[]" type="text" placeholder="Field No."/></div><div class="col-2 colorInput"></div><div class="col-2"><button class="remove-proposition-field propositionManage">Usuń pole</button></div></div>';
i++;
rodzic.append(input);
$(" #propositionsFields ").append(newField);
});
$('body').on('click', '.remove-proposition-field', function() {
$(this).parent('div').parent('div').remove();
});
});
Demo: https://jsfiddle.net/k95detc8/
The issue if because you add the element before is exist. And the colorInput content is added to all colorInput class. I have remove your first element and add last parameter for add only in the last element
$(document).ready(function() {
var addField = $(".add-proposition-field");
var removeField = $('.remove-proposition-field');
addField.click(function(e) {
e.preventDefault();
var i = $('.propositionField').size();
var color = getRandomColor();
var input = document.createElement("input");
input.className = "form-control";
input.setAttribute("value", color);
input.setAttribute("type", 'text');
var picker = new jscolor(input);
var newField = '<div class="row"><div class="col-8"><input autocomplete="off" class="form-control" name="proposition[]" type="text" placeholder="Field No."/></div><div class="col-2 colorInput"></div><div class="col-2"><button class="remove-proposition-field propositionManage">Usuń pole</button></div></div>';
i++;
$(" #propositionsFields ").append(newField);
$('.colorInput:last').append(input);
});
$('body').on('click', '.remove-proposition-field', function() {
$(this).parent('div').parent('div').remove();
});
});
function updateColor(jscolor) {
$('.color-picker').val(jscolor);
$(this).val(jscolor);
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
div{
width:100% !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="http://beta.leonardo.pl/afrisoexpert/public/css/fluidable.css" rel="stylesheet"/>
<div class="form-group" id="propositionsFields" >
<label class="col-md-4 control-label">Options</label>
<div class="row">
<div class="col-8">
<input class="form-control propositionField" name="proposition[]" type="text" />
</div>
<div class="col-2">
<input type="text" class="form-control jscolor {onFineChange:'updateColor(this)'}" />
<input type="hidden" class="color-picker" value="" />
</div>
<!-- /.col-2 -->
<div class="col-2">
<button class="add-proposition-field propositionManage">Add field</button>
</div>
<!-- /.col-2 -->
</div>
<!-- /.row -->
</div>
<!-- /.form-group -->