Skip elements within a container when querying DOM - dom

When using querySelectorAll or any DOM query method, I want to skip elements within a given sub-container from querying.
Example:
<div id="container-one">
<div>
<input type="text" name="first">
<input type="text" name="second">
<!-- skip below -->
<div id="container-two">
<input type="text" name="third">
<input type="text" name="fourth">
</div>
<div>
</div>
Suppose in the above case, if you are querying from #container-one element you want to skip elements within #container-two. So the query on #container-one should only return [first, second] elements and skip others (third, fourth).
Appreciate any inputs.

Try this:
document.querySelectorAll('div.container-one')[0].querySelectorAll(':scope > input')
Update(You can't use querySelectorAll for this then):
inputs = document.getElementsByTagName("input");
input_two = document.getElementById('container-two').getElementsByTagName('input');
var input_cont_two_name_array = [];
for(j=0;j<input_two.length;j++){
input_cont_two_name_array.push(input_two[j].name);
}
for(i=0;i<inputs.length;i++){
input_name_id = inputs[i].name;
if(input_cont_two_name_array.indexOf(input_name_id) == -1){
//do your stuff
}
}

Related

How to validate inputs on each step in a multi part form in vuejs?

I have created step in each tabs which represent the steps in the form. I have used v-if condition to check which step should be displayed. As of now the steps work perfectly fine when i click the next button. Even if the inputs are empty I am able to go to the next step. I want some validation on each step that will check if the input is empty and add a class to that input say "error-class". How do I do that in vuejs?
This is my form in .vue file.
<form id="product_form" enctype="multipart/form-data">
<!-- One "tab" for each step in the form: -->
<button type="button" v-if="step === 2 || step === 3 || step === 4" id="prevBtn1" #click.prevent="prev()"></button>
<div v-if="step === 1" class="tab">
<h3>Post a product</h3>
<div class="preview" id="preview">
</div>
<div class="single-holder">
<input type="text" name="pname" id="pname" placeholder="Title*" required="true" ref="pname">
</div>
</div>
<div v-if="step === 2" class="tab">
<h3>Describe your Product</h3>
<div class="descrip">
<textarea name="description" id="description" placeholder="Description" required="true"></textarea>
</div>
</div>
<div v-if="step === 3" class="tab">
<h3>Set Inventory</h3>
<div class="fixed-width">
<div class="single-holder">
<label>Quantity</label>
<input type="number" name="quantity" id="quantity" required="true">
</div>
</div>
</div>
<div v-if="step === 4" class="tab">
<h3>Share On</h3>
<div class="address-details-holder clearfix">
<div class="single-holder">
<input placeholder="_ _ _ _" id="zipcode" name="zipcode" maxlength="4" type="text" #keypress="onlyNumber">
</div>
</div>
</div>
</form>
This is my method in Vuejs
methods:{
onlyNumber ($event) {
let keyCode = ($event.keyCode ? $event.keyCode : $event.which);
if ((keyCode < 48 || keyCode > 57) && keyCode !== 46) { // 46 is dot
$event.preventDefault();
}
},
prev() {
this.step--;
},
next() {
this.step++;
//if(this.step===1){
// console.log(this.$refs.name.value);
//if(this.$refs.pname.value !== null){
// this.step++;
//}
//}
}
As of now the steps work fine if i remove the if condition in the function next() in methods. But I need input validations on each step so the user has to fill out the missing data in all the form fields.
I think you can use Vee Validate . It will help you check required in each input
<input v-validate="'required'" data-vv-as="field" name="required_field" type="text">
And return error message for that input if it false
<span>{{ errors.first('email') }}</span>

Add key eventlistener to last generated input field and stop it after typing

When I click a Button, a form of an unspecific number of input fields will be generated in my dom plus an empty input Field.
I want to add something like a keypress event to the last generated empty input field.
When I start typing, into the last empty input field, another input field should append. This new appended input field should get the keypress eventlistener and the input field I am in should loose the keypress eventlistener.
Here's how I did it(EDIT: added as code snippet):
$(document.body).on("input", ".service-input:last", function (e) {
var lastInput = $(".elementCtr.input-ctr input").last(),
inputID = (parseInt(lastInput.attr('name')) + 1);
$("#providerServicesForm .inputs").append('<div class="elementCtr input-ctr"><input id="service_' + inputID + '" type="text" value="" name="' + inputID + '"></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form accept-charset="UTF-8" name="providerServicesForm" id="providerServicesForm" method="post">
<div class="inputs">
<div class="elementCtr input-ctr"><input type="text" name="1" value="test1" id="service_1" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="2" value="test2" id="service_2" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="3" value="test3" id="service_3" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="3" value="" id="service_3" class="service-input"></div
</div>
</form>
This works fine so far.
But of course I want that this happens only with the first keypress.
After pressing a key, it should stop adding textfields. But when I type something in to the new added (last) textfield it should add a textfield again. But only 1 Textfield after pressing a key etc...
I can't stop the eventlistener after typing.
Does Keypress work with mobile devices?
The great thing about this sort of handler, is if you update the DOM with a new last element, the handler immediately switches to the new element - no need to use .off or .one.
$(document.body).on("input", ".service-input:last", function () {
var inputID = (parseInt($(this).attr('name')) + 1);
$("#providerServicesForm .inputs").append('<div class="elementCtr input-ctr"><input id="service_' + inputID + '" class="service-input" type="text" value="" name="' + inputID + '"></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form accept-charset="UTF-8" name="providerServicesForm" id="providerServicesForm" method="post">
<div class="inputs">
<div class="elementCtr">
<input id="service_0" type="text" class="service-input" value="" name="0">
</div>
<div class="elementCtr">
<input id="service_1" type="text" class="service-input" value="" name="1">
</div>
<div class="elementCtr">
<input id="service_2" type="text" class="service-input" value="" name="2">
</div>
</div>
</form>
One possible enhancement is to detect an empty string and remove the newly added input.
If you only want it to happen for once, why not create a counter and set it to 0. After it had happened, you can increase the counter to 1.
var counter=0;
$(document.body).on("keypress", $(".elementCtr.input-ctr input").last(), function () {
if(counter==0){
//put your logic here
counter++;
}
})

Foundation 5 & Abide: a custom validator for a set of checkboxes?

I would like to create a validator for abide for a set of checkboxes.
Let's consider a set of 5 checkboxes. The user is asked to check 3 max, and at least 1.
So, here is my work-in-progress code:
<div data-abide-validator='checkboxes' data-abide-validator-values='1,3'>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
</div>
<script>
$(document).foundation({
validators: {
checkboxes: function(el, required, parent) {
var countC = el.find(':checked').length;
alert(countC);
}
}
});
</script>
At this point, I just try to count the checked inputs. But it seems I can't even trigger the validator... I think I could manage to code my validation stuff if only I could figure out how to trigger it.
Indeed I didn't find many examples of the custom validator, and the official doc did not help me much.
Your HTML markup is not really "correct" for abide. You should be attaching the data-abide-validator attribute to the inputs, not the parent div. Additionally, you need some better markup so abide's default error display can work (and some better use of foundation's grid system to lay it out). I would point you toward the Abide Validation Page on Zurb's site for some examples of form markup.
I've taken the liberty of restructuring your markup to be something that is more becoming of a foundation layout:
<form action="/echo/html/" method="POST" data-abide>
<div class="row">
<div class="small-12 columns checkbox-group" data-abide-validator-limit="1,3">
<label>Check some boxes</label>
<small class="error">You have checked an invalid number of boxes.</small>
<ul class="small-block-grid-3">
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="1" /> 1
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="2" /> 2
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="3" /> 3
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="4" /> 4
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="5" /> 5
</label>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<button type="submit">Submit</button>
</div>
</div>
</form>
As to your JS code. It's not correct either. You need to address the abide -> validators namespace of the options, not just validators. I've rewritten your JS code to not only do that, but give the desired effect you wanted:
$(document).foundation({
abide: {
validators: {
checkbox_limit: function(el, required, parent) {
var group = parent.closest( '.checkbox-group' );
var limit = group.attr('data-abide-validator-limit').split(',');
var countC = group.find(':checked').length;
if( countC >= limit[0] && countC <= limit[1] ) {
group.find('small.error').hide();
//return true so abide can clear any invalid flags on this element
return true;
} else {
group.find('small.error').css({display:'block'});
//return false and let abide do its thing to make sure the form doesn't submit
return false;
}
}
}
}
});
In order to check adjacent elements when doing custom validation, you need to have something to target. The el variable in the validation function will be the DOM element of the input/field that is being validated. The required variable will tell you if the field is flagged as being required or not (boolean). The parent variable will be set to the "parent" of the field. I say "parent" because although the label tag is technically the parent of the input element, abide is smart enough to realize that the label is part of the field's element structure and skip over it to the li element instead.
From there, you need a way to identify a common parent. So I added the checkbox-group class to whatever element I decided to make the "parent" of all the checkboxes in the group. This is not a Foundation or Abide "magic" class, but rather something of my own creation for use in the validation function.
From there, you can easily trace the few lines of the validation function to see the workflow: Find the group container object, parse the limits off the container's data-abide-validator-limits attribute, count the number of checked inputs in the container, check if the number checked is between the limits, display/hide the error message and return true/false so abide knows if the field validated or not.
I've got a working Fiddle of it if you care to check it out yourself ;) Hopefully this was informative for you, and I wish you the best of luck playing with the awesome that is Foundation!

serialize array returning an empty array

I'm trying to grab some form data in my function but for some reason my fom returns an empty array when i try and run the function .serializeArray() on it. I've checked that to make sure it input element has a name I just can't figure out why this is happening
this is my form
<form id="uploadForm" name="form" action="{{nodeSocketUrl}}/upload?tenant=qa&envelope=true" method="POST" enctype="multipart/form-data" class="forms" style="left:15px">
<fieldset class="units-row">
<h3>Upload A Presentation</h3>
<label for="presentationFileUpload">Select a .ppt, .pptx, .pdf</label>
<input type="file" id="presentationFileUpload" name="presentationFile" onchange="angular.element(this).scope().onFileSelect(this)"/>
<hr>
<input type="submit" id="fileUploadBtn" class="btn btn-primary disabled" value="Upload" ng-click="uploadFile($event)" name="upload">
</fieldset>
</form>
This is my function which I'm hopping to get the form data from
$scope.uploadFile = function(e) {
e.preventDefault();
//$scope.form.preventDefault();
var dCheck = $('input[type="file"]').val();
console.log(e.currentTarget);
var form = $('#uploadForm').serializeArray();
console.log(form);
}
form returns an empty array any help with this would be appreacited
Why not think in pure angular way?
use can use
<input type="file" ng-model="filePath">
And next, get the file name in $scope.filePath

Example of jQuery Mobile site with conditional/branching questions

I'm trying to create a JQM survey with branching questions--i.e. in a survey with questions 1-3, if you choose a particular answer on question 1, a question is dynamically added between questions 1 and 2.
UPDATE: I made an attempt ( https://dl.dropbox.com/u/17841063/site2/index-c1.html#page2 ) that works by matching the value of a radio button to the name of a hidden div--if there's a match, it unhides the div. The problem right now is that if you change your answer back to an option that wouldn't trigger the conditional question, it doesn't re-hide. For example, clicking No or Unsure in question A1 causes question A2 to appear, but if you then click Yes in A1, A2 still remains...
<script type="text/javascript">
// Place in this array the ID of the element you want to hide
var hide=['A2','A4'];
function setOpt()
{
resetOpt(); // Call the resetOpt function. Hide some elements in the "hide" array.
for(var i=0,sel=document.getElementsByTagName('input');i<sel.length;i++)
{
sel[i].onchange=function()
{
if(this.parentNode.tagName.toLowerCase()!='div')
resetOpt(); // Hides the elements in "hide" array when the first select element is choosen
try
{
document.getElementById(this.value).style.display='';
}
catch(e){} ; // When the value of the element is not an element ID
}
}
}
window.addEventListener?window.addEventListener('load',setOpt,false):
window.attachEvent('onload',setOpt);
function resetOpt()
{
for(var i=0;i<hide.length;i++)
document.getElementById(hide[i]).style.display='none'; // Hide the elements in "hide" array
}
</script>
Here's are the radio buttons that use the script above:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>(Question A1) A prominent accident smokes on top of the blessed reactionary?</legend>
<input type="radio" name="aaa" id="aaa_0" value="notA2" />
<label for="aaa_0">Yes</label>
<input type="radio" name="aaa" id="aaa_1" value="A2" />
<label for="aaa_1">No</label>
<input type="radio" name="aaa" id="aaa_2" value="A2" />
<label for="aaa_2">Unsure</label>
</fieldset>
</div>
<div id="A2" data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>(Question A2) Does a married composite remainder the shallow whistle??</legend>
<input type="radio" name="bbb" id="bbb_0" value="" />
<label for="bbb_0">Yes</label>
<input type="radio" name="bbb" id="bbb_1" value="" />
<label for="bbb_1">No</label>
<input type="radio" name="bbb" id="bbb_2" value="" />
<label for="bbb_2">Unsure</label>
</fieldset>
</div>
If anyone has ideas about fixing this, or examples of other ways to do branching forms, I'd be very grateful!
Thanks,
Patrick
I played around a little bit with your example, removed all your plain JavaScript and added some jQuery Mobile style script, see working example here
<script>
$("input[type='radio']").bind( "change", function(event, ui) {
var mySelection = $('input[name=aaa]:checked').val();
//alert(mySelection);
if (mySelection == "A2") {
$('#A2').removeClass('ui-hidden-accessible');
} else {
$('#A2').addClass('ui-hidden-accessible');
};
});
</script>