In my Javascript I'm trying to validate the user's input.
Is there a way i can show ( define the text via .html() ) the (upper) closest element with classname "xy"
my HTML-File looks like this:
<div class=" row validate" style="display:none;">
<div class="col-lg-1"></div>
<div class="col-lg-7"><p class="validation_text"></p></div>
</div>
<div class="row">
<div class="col-lg-1 col-sm-0 col-xs-12"></div>
<div class="col-lg-3 col-sm-3 col-xs-12"><a href="#" data-
toggle="tooltip" data-placement=" auto top" title="Text">Information</a></div>
<div class="col-lg-2 col-sm-2 col-xs-12"><input id="xy" name="xy"
type="search" class="form-control" maxlength="2" onChange="validate(this);">
</div>
</div>
and in My JS-File:
function validate(){
var regex = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?()]/);
var box = ['xy','xyyy];
var element;
element = document.getElementById(box[i]);
for (i=0; i < box.length; i++){
if(regex.test(element.value)){
$(element).parent().parent().prev().show();
element.style.border = '2px solid red';
$(".validation_text").eq([i]).html("your input contains regex");
}
}
}
everything works fine, the only problem i've got is the last part. the validation_text is not showing. Does anybody know why?
eq() expects an integer and you are giving it an array
$(".validation_text").eq([i])
should be
$(".validation_text").eq(i)
Related
Edited, to provide more information
This is my HTML
<div class="quote-info">
<div class="quote-item">
<div class="form-group">
<label for="list-item1">Item</label>
<input type="text" class="form-control">
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="quantity-item1">Quantity</label>
<input type="number" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="price-item1">Price</label>
<input type="number" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="total-item1">Total</label>
<input type="text" class="form-control">
</div>
</div>
</div>
</div>
<button class="btn add-item">
New Item
</button>
// Javascript
var quoteInfo = document.querySelector('div.quote-info')
var newDiv = quoteInfo.lastElementChild
var addButton = document.querySelector('.add-item')
addButton.addEventListener('click', () => {
quoteInfo.appendChild(newDiv.cloneNode())
})
I'm trying to make the button to be clickable and create a new div of <quote-item> inside of <quote-info> but nothing happen
What is wrong with my code?
You mentioned that you tried after() and cloneNode(). There's no after() method for DOM elements, but there is appendChild(). So that may have been your mistake.
const div = document.querySelector("div.your-cart")
const input = div.firstElementChild;
const button = document.querySelector("button.new-item")
button.addEventListener("click", event =>
div.appendChild(input.cloneNode())
)
<div class="your-cart">
<input class="item" type="text">
<input class="item" type="text">
</div>
<button class="new-item">CLICK ME</button>
You can use
Document.createElement to create the input tag and then append it to the target div by using Node.appendChild
var container= document.querySelector(".your-cart");
var input = document.createElement("input");
input.type = "text";
input.className = "item";
container.appendChild(input);
hi you can do it like below with jquery:
1- raw html injection like so:
$('.your-cart').append('<input class="item" type="text"/>');
2- using existing element:
var $input = $('.your-cart').children().eq(0).clone();
$('.your-cart').append($input);
you can add as much as element you need to '.your-cart'
In the form I am making, there is a section that requires users to enter the amount of people in their family. After they provide it, the form generates enough input fields so that the user can enter information for each family member.
What I am having trouble with is none of the attributes that I am trying to apply to the input element actually work.
function addHouseMembers(that){
var family = document.getElementById("family-input-container");
while(family.hasChildNodes()){
family.removeChild(family.lastChild);
}
for(var i = 1; i < that.value; i++){
family.appendChild(document.createTextNode("Family Member " + (i+1)));
family.appendChild(document.createElement("br"));
//name
family.appendChild(document.createTextNode("Name: " ));
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i + "_name";
input.pattern = "/^[a-zA-Z ]*$/";
input.required = true;
family.appendChild(input);
family.appendChild(document.createElement("br"));
}
}
The parameter that refers to the input where the user would put in the number of people in their family.
And here is the relevant HTML:
<form>
<div class="form-group">
<label class="col-lg-3 control-label">What is the total amount of people living in your household?</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group">
<input type="text" class="form-control" name="household-size" required onchange="addHouseMembers(this);"/>
</div>
</div>
</div>
<div class="form-group", id="family-info">
<label class="col-lg-12">Information for other Family Members</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group" id = "family-input-container" required>
</div>
</div>
</div>
</form>
The element shows up as it should, and is submitted with the form when the user hits the submit button, but the regex pattern and required attributes are not enforced.
in addHouseMembers(that) the value of that is a string, not a number, and you have to check if is value can be 'translated' in an integer value.
use the "onchange" event on the input field household-size is not a good idea because this event is triggered each time a digit of the number entered, which has the effect of erasing and completely rewrite the family-input-container part
I Imagine you are looking for something like that ?
const myForm = document.getElementById('my-form')
, familyElm = document.getElementById('family-input-container')
, parserDOM = new DOMParser()
;
function newHouseMember(ref)
{
let div=
` <div>
Family Member ${ref}<br>Name: <br>
<input type="text" name="member${ref}_name" pattern="/^[a-zA-Z ]*$/" required >
</div>`
return parserDOM.parseFromString( div, 'text/html').body.firstChild
}
myForm.btPeoples.onclick=_=>
{
let nbPeoples = parseInt(myForm['household-size'].value)
if (!isNaN(nbPeoples) && nbPeoples > 0 )
{
familyElm.innerHTML = ''
for (let i=1; i<=nbPeoples; i++)
{
familyElm.appendChild( newHouseMember(i) )
}
}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" >
<form id="my-form">
<div class="form-group">
<label class="col-lg-3 control-label">What is the total amount of people living in your household?</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group">
<input class="form-control" name="household-size" required value="" placeholder="number of peoples" pattern="\d*" />
<button name="btPeoples" class="btn btn-info" type="button" >check it!</button>
</div>
</div>
</div>
<div class="form-group", id="family-info">
<label class="col-lg-12">Information for other Family Members</label>
<div class="col-lg-3 inputGroupContainer">
<div class="input-group" id="family-input-container">
</div>
</div>
</div>
</form>
I want to assign a new class to a label when it's corresponding input element has focus.
I have a form with 10 input fields and 10 labels for each.
const inputFields = document.querySelectorAll('.form-control');
console.log(inputFields);
jQuery(inputFields).on('focus', function() {
for (let i = 0; i < inputFields.length; i++) {
if (jQuery(inputFields[i]).hasFocus) {
jQuery(inputFields[i].closest('label')).addClass(' active');
console.log('hello Wurst');
} else {
jQuery(inputFields[i].closest('label')).removeClass(' active');
console.log('hello secondWurst');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-5 first_col">
<div data-field-wrapper="fld_1854024" class="form-group" id="fld_1854024_1-wrap">
<label id="fld_1854024Label" for="fld_1854024_1" class="control-label">City</label>
<div class="">
<input type="text" data-field="fld_1854024" class=" form-control" id="fld_1854024_1" name="fld_1854024" value="" data-type="text" aria-labelledby="fld_1854024Label">
</div>
</div>
</div>
I have tried to grab all of the form input elements into a const, then loop through each to see if it has focus. If that particular one has focus, then I want to give the label for that field (and only that field) an additional CSS class.
How do I look for the input that has the cursor focus, and apply a new class to that input's label?
This is DOM traversal and is easy with jQuery - on focussing the input - go up to the nearest form-group using .closest() and then down to the nearest label within that form-group, using.find().
Note the line that removes the active class from all labels - this prevents you needing to know which was previously active and ensures that only the currently focussed input's label gets the active class.
$('document').ready(function(){
$('.form-control').on('focus',function(){
$('label').removeClass('active');
$(this).closest('.form-group').find('label').addClass('active');
});
})
.col-sm-5 {
margin: 16px;
}
label.active {
color: red;
font-weight: bold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-5 first_col">
<div data-field-wrapper="fld_1854024" class="form-group" id="fld_1854024_1-wrap">
<label id="fld_1854024Label" for="fld_1854024_1" class="control-label">City</label>
<div class="">
<input type="text" data-field="fld_1854024" class=" form-control" id="fld_1854024_1" name="fld_1854024" value="" data-type="text" aria-labelledby="fld_1854024Label">
</div>
</div>
</div>
<div class="col-sm-5 second_col">
<div data-field-wrapper="fld_1854025" class="form-group" id="fld_1854025_1-wrap">
<label id="fld_1854025Label" for="fld_1854025_1" class="control-label">State</label>
<div class="">
<input type="text" data-field="fld_1854025" class=" form-control" id="fld_1854025_1" name="fld_1854025" value="" data-type="text" aria-labelledby="fld_1854025Label">
</div>
</div>
</div>
I am using a diective in ng-repeat which when i click i pass date and time to the function showAppointmentForm but here the problem is when I click on first index of loop i get date and time displayed in modal box but when I click on second ,third and so on its values are coming as function parameters but not displayed.Is this something problem with using directives in for loop.Can anyone please suggest help.Thanks.
Using directive in template,
<div data-ng-repeat="doctor in doctors">
<appointment-timings data-ng-if="appointments" appointments="appointments" physician="doctor.npi" width="2"></appointment-timings>
</div>
My appointmnt directive,
$scope.showAppointmentForm = function(date,time) {
$scope.appointmentData = {};
$scope.appointmentData.physician = $scope.physician;
$scope.appointmentData.date = '';
$scope.appointmentData.time = '';
$scope.appointmentData.date = date.toString();
$scope.appointmentData.time = time;
$scope.submitted = false;
$timeout(function () {
$scope.$apply();
$('#appointments').modal('show');
},500);
}
My Directive html,(A modal box)
<div class="date-time">
<div class="col-md-6 col-xs-6">
<div class="input-group">
<span class="input-group-addon"><b>DATE</b></span>
<input type="text" class="form-control" ng-model="appointmentData.date" disabled>
</div><!-- /input-group -->
</div>
<div class="col-md-6 col-xs-6">
<div class="input-group">
<span class="input-group-addon"><b>TIME</b></span>
<input type="text" class="form-control" ng-model="appointmentData.time" disabled>
</div>
</div>
</div>
<div class="scheduled-hours" id="scheduled-scroll">
<ul>
<li data-ng-click="showAppointmentForm(date, time)" data-ng-repeat="time in times">{{time}}</li>
</ul>
</div>
I am trying to append a div multiple times when clicking a button, the problem is that is only appending once. I need to append same div as user keeps clicking.
DIV I need to append multiple times is stored in a variable named $htmlDivForm in the jquery code.
I'm using bootstrap.
HTML code:
<div class="container">
<div class="row">
<div class="col-md-3">
<form id="formUser" action="index.html" method="post">
<div class="text-center">
<button id="moreFieldsBtn" class="btn" type="button" name="button">+</button>
</div>
</form>
</div>
<div class="col-md-9">
More Content...
</div>
</div>
</div>
jquery code:
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
//Add input text field
$($moreFieldsBtn).click (function() {
$($formUser).append($htmlDivForm);
});
I had gone through your question.
I have Updated the example.
Removed the Object and just inserting plain HTML
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
var htmltext = '<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>'
//Add input text field
$($moreFieldsBtn).click (function() {
$($formUser).append(htmltext);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-3">
<form id="formUser" action="index.html" method="post">
<div class="text-center">
<button id="moreFieldsBtn" class="btn" type="button" name="button">+</button>
</div>
</form>
</div>
<div class="col-md-9">
More Content...
</div>
</div>
</div>
<div>
You can't append the same div multiple times, you need to instantiate new divs and attach those. You also don't need to re-wrap the jQuery objects to attach the handlers:
var $moreFieldsBtn = $("#moreFieldsBtn");
var $formUser = $("#formUser");
//Add input text field
$moreFieldsBtn.click(function() {
var $htmlDivForm = $('<div class="form-group"><label class="labelName" for="inputText">Nombre</label><input class="form-control inputTextField" type="text" name="inputText" value=""></div>');
$formUser.append($htmlDivForm);
});