Jquery help create input field based on another - javascript

I am trying to create an input field when the Add input is clicked.
The input created with Jquery should be the same as the closest input field but just with info added to the name.
When the Add input is clicked the text should change to "Remove input" and if it is clicked the created input field should be removed.
My HTML:
<div class="input string optional">
<label for="company_count" class="string optional"> count</label>
<input type="text" size="50" name="company[count]" maxlength="255" id="company_count" class="string optional">
<p class="addinput">Add input</p>
</div>
<div class="input string optional">
<label for="company_navn" class="string optional"> Navn</label>
<input type="text" size="50" name="company[navn]" maxlength="255" id="company_navn" class="string optional">
<p class="addinput">Add input</p>
</div>
My Jquery
$('.addinput').toggle(function() {
}
});
Update:
The input field:
<div class="input numeric integer optional"><label for="company_prisar" class="integer optional"> Pris 1. år</label><input type="number" step="1" size="50" name="company[prisar]" id="company_prisar" class="numeric integer optional"></div>
When the add input is clicked this input is added:
<input type="number" step="1" size="50" name="company[prisarinfo]" id="company_prisarinfo" class="numeric integer optional">

If I understand your question correct then something like this should solve the problem:
$('button.add', '#companyinfo').live('click', function(e) {
var element = $(this).parents('.input').find('input').last().clone().prop('value','');
var counter = $(this).parents('.input').find('input').length + 1;
var newname = element.prop('id') + '_' + counter;
element.prop('name', newname);
element.insertAfter($(this).parents('.input').find('input').last());
$('button.remove').removeProp('disabled');
})
$('button.remove', '#companyinfo').live('click', function(e) {
$(this).parents('.input').find('input').last().remove('input');
if ($(this).parents('.input').find('input').length == 1) {
$(this).parents('.input').find('button.remove').prop('disabled', 'disabled');
}
});
Note that I've modified you html a bit, you can see a working live demo at jsFiddle.

I think you have a typo, it should read:
$('p.addinput').toggle(function(){});
Could you expand upon what you want the function to do? It's not clear to me.

Related

Need help to remove items dynamically using pure javascript

Requirements:
A new text box should appear with a delete button at closing after clicking '+Add Stop'.
If a delete(x) button is clicked, the respective text box should be removed and Stop #(sequence numbering) should be changed as well.
Need help on:
I have tried to achieve the both above requirements. I get results for #1. But for #2, After adding more items, the delete button works/removes only the last added item only but it should work the same for all items.
Stop # sequence number should be maintained after the removal of an item(s). I need help with this logic also.
HTML:
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option>
</select><br/><br/>
<label for="fullname">Name: </label><input id="fullname" name="name" size="20" type="text" maxlength="20" placeholder="John Doe" required /><br/><br/>
<label for="phone">Phone: </label><input id="phone" name="phone" maxlength="12" type="tel" placeholder="012-345-6789" required /><br/><br/>
<label for="email">Email: </label><input id="email" name="email" size="30" type="email" maxlength="30" placeholder="contact#example.com" required /><br/><br/>
<label for="ptime">Pickup time </label><input id="ptime" name="pickup-time" type="time" required /><br/><br/>
<label for="pdate">Pickup Date </label><input id="pdate" name="pickup-date" type="date" required /><br/><br/>
<div id="add_stop_here">
</div>
<input type="button" id="add" value="+Add Stop" onclick="test();" />
</form>
JavaScript:
var counter = 0;
function test () {
counter += 1;
var addHtml = '\
<div class="input-box">\
<label for="stop'+counter+'">Stop '+counter+':</label>\
<input type="text" id="stop'+counter+'" name="stop"/ > <a id="rmv'+counter+'" class="remove_stop" href="#">x</a>\
</div>';
var add_hre = document.getElementById("add_stop_here");
add_hre.innerHTML += addHtml;
document.querySelector("#rmv"+counter)
.addEventListener('click', function(){
var removeEl = this.parentNode;
add_hre.removeChild(removeEl);
});
}
Some issues to take care of:
To make this work, I would refrain from using id attributes that have a sequential number. It is not best practice.
Instead, in order to link a label element with its input element, make the input element a child of the corresponding label element. Now the id and for attributes are no longer needed.
Don't use innerHTML += as that will reset the values of the inputs that are already in the document, and will remove the event listeners. Instead use insertAdjacentHTML.
To keep the numbering in pace, use a span element that only has that number, and renumber all those span elements after every change. You can also use it after an insert, just to keep the code clean, and avoid that you need to maintain a counter.
To avoid that you need to attach a new event handler for every new element, listen to click events on the container element, and then check in that single handler which element was clicked. This is called event delegation.
Don't name your function test. Give it a useful name, like insertBusStop.
Instead of binding that handler via HTML attribute, bind it via code.
For multi-line strings you can use back tick delimiters (template literals)
I'd suggest that after clicking the Add button, the focus is put on the newly created input element. This facilitates the input procedure for the user.
Here is how that would work:
var add_hre = document.getElementById("add_stop_here");
document.getElementById("add").addEventListener("click", addBusStop);
function addBusStop() {
var addHtml = `
<div class="input-box">
<label>
Stop <span class="stop_number"></span>
<input type="text" name="stop"/> <a class="remove_stop" href="#">x</a>
</label>
</div>`;
add_hre.insertAdjacentHTML("beforeend", addHtml);
renumber();
add_hre.querySelector(".input-box:last-child input").focus();
}
function renumber() {
let i = 1;
for (let labelSpan of add_hre.querySelectorAll(".stop_number")) {
labelSpan.textContent = i++;
}
}
// Use event delegation
add_hre.addEventListener('click', function(e) {
if (!e.target.classList.contains("remove_stop")) return;
var removeEl = e.target.parentNode.parentNode; // need one more level now
add_hre.removeChild(removeEl);
renumber();
});
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop"/>
You can do this with each() and find() function easily.
var counter = 0;
$("#add").click(function () {
counter++;
$("#add_stop_here").append(
'<div class="input-box"><label for="stop' +
counter +
'">Stop' +
counter +
': <input type="text" id="stop' +
counter +
'" name="stop"/ ></label> <a id="rmv' +
counter +
'" class="remove_stop" href="#">X</a></div>'
);
});
$(document).on("click", ".remove_stop", function () {
$(this).closest("div").remove(); //use closest here
$("#add_stop_here .input-box").each(function (index) {
$(this)
.find("label:eq(0)")
.attr("id", "stop" + (index + 1));
$(this)
.find("label:eq(0)")
.html("Stop" + (index + 1) + '<input type="text" name="stop" />');
});
counter--;
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option></select
><br /><br />
<label for="fullname">Name: </label
><input
id="fullname"
name="name"
size="20"
type="text"
maxlength="20"
placeholder="John Doe"
required
/><br /><br />
<label for="phone">Phone: </label
><input
id="phone"
name="phone"
maxlength="12"
type="tel"
placeholder="012-345-6789"
required
/><br /><br />
<label for="email">Email: </label
><input
id="email"
name="email"
size="30"
type="email"
maxlength="30"
placeholder="contact#example.com"
required
/><br /><br />
<label for="ptime">Pickup time </label
><input id="ptime" name="pickup-time" type="time" required /><br /><br />
<label for="pdate">Pickup Date </label
><input id="pdate" name="pickup-date" type="date" required /><br /><br />
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop" />
</form>

Input type="text" currency validation

I currently have an input type="text" that I transform into a currency value on the "keyup" event. In order to keep this functionality (works fine), the input type has to be set to "text". At the same time, I would like to have a minimum value of "100.00" set to it.
Any way I can accomplish this? Also, would I able to customize my jquery validation message to say "Minimum Amount $100.00"?
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required id="balance" name="balance" type="text" class="number" />
You can add this property in your input filed: minlength="5"
<input required id="balance" name="balance" type="text" class="number" minlength="5" />
And in your JS code you can add a 'if' statement to check that this input contain at least 5 char.
Furthermore you can add the same 'if' statement in your back-end to check it again.
Thank you all for your input.
I've ended up keeping the input type="text" for the number of digits users can type in and called a function to check the input value against the 100.
function checkAmount() {
var valueBalance = $("#balance").val();
var valueNumberBalance = parseFloat((valueBalance).replace(/[^\d\.]/, ''));
if (valueNumberBalance < 100) {
$("#balance").get(0).setCustomValidity("Minimum Amount of $100.00");
}
else {
$("#balance").get(0).setCustomValidity("");
}
}
A snippet created using the type="number" instead of type="text" on the input still allows the jQuery functionality to work.
The validation message is HTML5 and not jQuery as you did not provide that code. I did the following:
Changed to type="number"
Added min="100"
Added step="0.01" to handle currency stepping
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Text input (original): <input required id="balance" name="balance" class="number" type="text" /><br />
Number input: <input required id="balance" name="balance" class="number" type="number" min="100" max="99999" step="0.01" /><br />
<input type="submit" />
<small>Enter less than 100 and press 'submit' to see validations.</small>
</form>
you can try to currency validation using regex
<div class="col-sm-3 form-group">
<b>Premium :*</b><br>
<p><input type="text" class="form-control" oninput="this.className = ''" name="premium" id="premium" valideAtt="currency" title="Premium" onblur="defaultValidation(this)"></p>
<span id="er_premium" style="display: block; width:100%; float: left;"></span>
</div>
<script type="text/javascript">
var REG_CURRENCY = /(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$/;
function defaultValidation(src){
var getAttributeValue=src.attributes.valideAtt.value;
if(getAttributeValue=="currency"){
if(!src.value.match(REG_CURRENCY)){
$("#"+src.id).addClass("invalid");
$("#er_"+src.id).html("<span style=\"color:red\">Please Enter Valide currency Value.<\span>");
return false;
}else{
$("#er_"+src.id).html("");
return true;
}
}
}
<script>

How to assign javascript variable value to HTML Attribute?

I am having 2 text box.. Value of first text box should been an length of second text box.. Eg: If user gives First text box value as "10", then my second text box should not allow user to type more than 10 characters..
Here is my code..
function field_length() {
var fieldValue = document.getElementById('Length').value;
alert(fieldValue);
}
<input type="text" name="Length[]" maxlength="2" class="required" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field length" class="form-control">
<input type="text" name="Label[]" class="required" id="Label" maxlength="" onClick="field_length();" placeholder="Field Label" class="form-control">
In this code what i did was.. if user is gives value for first field as "5", on tap of second field it will alert the value.. But i want that value to be assigned to Maxlenght attribute. Give me some idea..
Get length and set maxLength attribute.
function field_length(){
var length = $("#Length").val();
$("#Label").attr("maxlength", length)
}
You can use setAttribute
<script type="text/javascript">
function field_length()
{
var fieldValue= document.getElementById('Length').value;
document.getElementById("Label").setAttribute('maxlength',fieldValue);
}
</script>
<input type="text" name="Length[]" maxlength="2" class="required" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field length" class="form-control">
<input type="text" name="Label[]" class="required" id="Label" maxlength="" onClick="field_length();" placeholder="Field Label" class="form-control">
Try this:
$("#Label").attr("maxlength", length);
or
$("#Label").prop("maxlength", length);
NOTE:
As of jQuery 1.6. , the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Give two text boxes the same value one is filled in using Javascript or jQuery

I have 2 textboxes with a type="number".
1 textbox is my 'master' textbox, then I have another subsequent textbox that I would like that IF the 'master' textbox is filled in with a number, the subsequent textbox would get the same value.
I thought about using the data- attribute but I am not sure how to target if the 'master' textbox is filled then, then subsequently put the same value in the sub textbox(es) with the same data- attribute.
In my example below I also use spans to create plus and minus buttons that adjust the value based on the value. This is in the JS section.
My current HTML is as follow:
<div id="masterTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
<!--Values from Master Textboxes should populate into these textboxes as well.-->
<div id="subTextboxes">
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<span class="addBtn AddMinusButton">+</span>
<span class="minusBtn AddMinusButton">-</span>
<input type="number" value="" placeholder="0" data-attendees="Child" />
<span class="addBtn AddMinusButton">+</span>
</div>
Javascript
<script>
$(document).ready(function () {
/*Add an minus buttons for variants*/
$(".AddMinusButton").on('click touchstart', function (event) {
event.preventDefault();
//Add button active style for touch.
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var newVal = oldValue;
//Hide .decButton for oldValue
if (newVal == 0 || oldValue == 0 ) {
oldValue = 0;
}
else { $button.parent().find(".minusBtn").show(); }
if ($button.text() == "+") {
newVal = parseFloat(oldValue) + 1;
// Don't allow decrementing below zero
if (oldValue >= 1) {
newVal = parseFloat(oldValue) - 1;
}
}
$button.parent().find("input.attendeeQuantityInput").val(newVal);
//Sub textboxes should take value of master textboxes. Is this correct syntax?
//This is probably wrong.
$('#subTextboxes input').data("attendee").val(newVal);
});//End button click
});
</script>
I hope this makes sense on what I am trying to get out of this.
Thanks in advance.
I would like that IF the 'master' textbox is filled in with a number,
the subsequent textbox would get the same value.
You can do it like this:
<p>
<label>Master 1: <input type="number" id="master1" placeholder="0" /></label><br>
<label>Dependant 1: <input type="number" class="dependant1" placeholder="0" /></label>
</p>
<p>
<label>Master 2: <input type="number" id="master2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label><br>
<label>Dependant 2: <input type="number" class="dependant2" placeholder="0" /></label>
</p>
And in the JS:
$("input[id^='master']").on("change", function(){
var no = this.id.replace("master", "");
var selector = ".dependant" + no
$(selector).val(this.value);
});
This makes use of jQuery's attribute starts with selector and will work for any number of inputs provided the class names match.
Demo
You could do this:
HTML:
<div id="masterTextboxes">
<p>Master</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
<div id="subTextboxes">
<p>Sub</p>
<input type="number" value="" placeholder="0" data-attendees="Adult" />
<input type="number" value="" placeholder="0" data-attendees="Child" />
</div>
JS:
// On change in master inputs...
$("#masterTextboxes input", this).on("change", function() {
// Store Master inputs in master variable and Sub inputs in sub variable.
var master = $("#masterTextboxes input"),
sub = $("#subTextboxes input");
// Match master and sub values by using the master array key as reference.
$(sub[$.inArray($(this)[0], master)]).val( $(this).val() );
});
The jQuery code relies on the condition that the Sub inputs follow the same order as the Master's inside each respective div.
JSFiddle:
Here's a working JSFiddle for reference.

Check if text box is empty or not, then put attributes

Disable the other textbox if the textbox(4) is filled. I have a multiple text boxes in my div
For instance:
If I put a text in textbox(4), then the textbox(1) will becomes disable. Then if I remove the text in the textbox(4), then the text box for the textbox(1) will becomes enable.
Here is the sample html:
<div class="main-wrapper">
<div class="form-text-wrapper">
<div><input type="text" class="form-text" value="" name="text1" id="text1"></div>
<div><input type="text" class="form-text" value="" name="text2" id="text2"></div>
<div><input type="text" class="form-text" value="" name="text3" id="text3"></div>
<div><input type="text" class="form-text" value="" name="text4" id="text4"></div>
</div>
</div>
My code doesn't seems to work, I'm not sure what's wrong with my code.
Here is my js code:
$('.main-wrapper').each(function(){
var name = $('#text4', this).val();
var disForm = $('#text1');
if ($(name.length >= 1)) {
$(disForm, this).attr('disabled', 'disabled');
} else {
$(disForm, this).removeAttr('disabled');
}
});
Please help... Thank you!!!
jQuery(function($) {
//change event handler which gets executd whenever the value of #test4 is chaned
$('#text4').on('change', function() {
//find all the input elements under the current .form-text-wrapper and except #test4 and set its disabled status based on #text4's value
$(this).closest('.form-text-wrapper').find('input').not(this).prop('disabled', this.value.length)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="main-wrapper">
<div class="form-text-wrapper">
<div><input type="text" class="form-text" value="" name="text1" id="text1"></div>
<div><input type="text" class="form-text" value="" name="text2" id="text2"></div>
<div><input type="text" class="form-text" value="" name="text3" id="text3"></div>
<div><input type="text" class="form-text" value="" name="text4" id="text4"></div>
</div>
</div>
Ok, so a few issues with what you are doing.
Firstly you are needing to execute your code every time one of those text boxes changes. You can wrap that functionality into a function and add it to the change event on each of the textboxes. I have added an example below. NB the example could be alot better than explicitly adding the change to each of the textboxes but I'll leave that for you to do.
Secondly you were executing your comparison for if the length was greater than 0 inside a jquery wrapper ($(name.length >= 1)) -> Don't. I've removed that as well in the code sample.
Thirdly I'm a little confused by the requirement. Are you wanting it to toggle disabled/not disabled for just the first text box? REading your code that's what it looked like you were trying to achieve. If you are wanting to disable all of the rest of the text boxes then Arun P Johny's function will do what you want.
function onTextChange(){
console.log('running');
$('.main-wrapper').each(function(){
var name = $('#text4', this).val();
var disForm = $('#text1');
if (name.length >= 1) {
$(disForm, this).attr('disabled', 'disabled');
} else {
$(disForm, this).removeAttr('disabled');
}
});
}
$('#text1').on('change', onTextChange);
$('#text2').on('change', onTextChange);
$('#text3').on('change', onTextChange);
$('#text4').on('change', onTextChange);
http://jsfiddle.net/jtgs5kcj/1/

Categories