How to get value from dynamic create input in Meteor? - javascript

I have created a custom form and added some jquery for dynamic inputs, but I can't get values from these generated inputs (Elements, Link, Image). Here are my form and code.
Template
This is my template for this form
<form id="workForm" class="workAdd">
<label>Title</label>
<input type="text" name="title" id="title" class="form-control">
<label>Live Link</label>
<input type="text" name="llink" id="llink" class="form-control">
<label>Elements Used In This Project</label>
<div class="row" id="eleContainer">
<div class="eleRow">
<div class="col s6 m6 l6">
<label>Element</label>
<input type="text" name="elements[]" id="elementsid[]" class="form-control">
</div>
<div class="col s6 m6 l6">
<label>Link</label>
<input type="text" name="elinks[]" id="elinksid[]" class="form-control" >
</div>
</div>
</div><!--row-->
<div class="row">
<div class="col s6 m12 center">
<a class="btn-floating waves-effect waves-light" id="addElements"><i class="fa fa-plus"></i></a>
</div>
</div>
<div class="row" id="imgContainer">
<div class="imgRow">
<label>Image</label>
<input type="text" name="image[]" id="imageid[]" class="form-control" >
</div>
</div>
<div class="row">
<div class="col s6 m12 center">
<a class="btn-floating waves-effect waves-light" id="addImages"><i class="fa fa-plus"></i></a>
</div>
</div>
<label>Detail</label>
<textarea id="detail" class="materialize-textarea" name="detail" data-length="120"></textarea>
<button type="submit" id="work-submit" thisId="" class="btn btn-primary">Submit</button>
Meteor
And this is my submit event I have created for this form.
Template.addworkTemp.events({
"submit .workAdd": function(event) {
var title = event.target.title.value;
var llink = event.target.llink.value;
var elements = event.target.elements.value;
var elinks = event.target.elinks.value;
var images = event.target.images.value;
var detail = event.target.detail.value;
return false;

There's a good tutorial on meteor forms that might be useful to you. This tutorial is based on blaze which is what you're using.
Firstly you can attach your handler to the form instead of to the workform class.
Template.addWorkTemp.events({
'submit form'(event) {
...
}
});
Then you should prevent the default form action:
Template.addWorkTemp.events({
'submit form'(event) {
event.preventDefault();
...
}
});
The event object has a target property which has properties for every field based on the name attached to them in the html.
Template.addWorkTemp.events({
'submit form'(event) {
event.preventDefault();
console.log(event.target.llink.value);
...
}
});
I have no idea why you're appending [] to the field names. I'm not sure those are valid in that context.
There's a related answer that shows how to access the form elements via the template object which is an optional second parameter to your event handler. That might also help you.
When I'm debugging things like this I normally set a breakpoint (using the browser's development tools) at the first line of the event handler then inspect the event to make sure I understand what's inside.

Related

Materialize CSS empty fields validation on submission

First of all, thanks for your time reviewing my question and trying to help me. I have been working on an App where I use Materialize CSS form to gather user's inputs. However, I have been having a hard time to validate empty fields when the user press the submit button.
Below is my code, so you can have a better idea of what I have. I need to come up with some javascript to validate empty fields when the user press the submit button on the form. I am having a hard time to create this, since I have nested object to fetch to my API. I tried creating a for in loop to iterate on the object but had no success on it.
Any insights on this would be highly appreciated!
Thanks Again
let btnSave = document.getElementById("btnSaveGift");
btnSave.addEventListener("click", APP.addGift);
addGift() {
//user clicked the save gift button in the modal
let gift = {
name: document.getElementById("name").value,
price: document.getElementById("price").value,
store: {
name: document.getElementById("storeName").value,
productURL: document.getElementById("storeProductURL").value
}
}
//validating the inputs - still working on it.
}
<div class="modal modal-fixed-footer center" id="modalAddGift">
<div class="modal-content">
<h4>New Gift idea</h4>
<p>Why not add another idea?</p>
<form class="col s12">
<div class="row">
<div class="input-field col s12 black-text">
<input id="name" type="text" class="validate black-text" class="validate" required=""
aria-required="true"/>
<label for="name" class="black-text">Idea</label>
<span class="helper-text" data-error="please try again"></span>
</div>
</div>
<div class="row">
<div class="input-field col s12 black-text">
<input id="price" type="number" inputmode="numeric" class="validate black-text" class="validate" required=""
aria-required="true"/>
<label for="price" class="black-text">Price</label>
<span class="helper-text" data-error="invalid price"></span>
</div>
</div>
<div class="row">
<div class="input-field col s12 black-text">
<input id="storeName" type="text" class="validate black-text" class="validate" required=""
aria-required="true"/>
<label for="storeName" class="black-text">Store Name</label>
<span class="helper-text" data-error="please try again"></span>
</div>
</div>
<div class="row">
<div class="input-field col s12 black-text">
<input id="storeProductURL" type="url" class="validate black-text" class="validate" required=""
aria-required="true"/>
<label for="storeProductURL" class="black-text">Website</label>
<span class="helper-text" data-error="invalid URL"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer light-blue">
<a
href="#!"
id="btnSaveGift"
class="modal-close waves-effect waves-green btn-flat white-text"
>Save Gift Idea</a
>
</div>
</div>
Validating your inputs values shouldn't be that difficult, since the addGift() function gets called when the submit button is clicked and the gift objct is generated within it. then your validation can take effect using a simple if statement:
// validating
if(!gift.name || !gift.price
|| !gift.store.name || !gift.store.productURL ){ // This checks for any false value
// What action you want to take goes here
} else{
// What to do when all fields are true goes here!
}

how to append an existing form on button click using jQuery

Given some html, a form named InterfacesIx and a button named addInterfacesIx
<div class="step-new-content white-text">
<p class="text-monospace"><small>helps you rollout a configlet about blahblah</small></p>
<form name="InterfacesIx">
<div class="row">
<div class="md-form col-12">
<input type="text" name="xxx" class="form-control white-text" placeholder="123"><label for="xxx">asn</label>
</div>
<div class="md-form col-12">
<textarea name="yyy" class="md-textarea form-control white-text" rows="3"></textarea><label for="yyy">notes</label>
</div>
</div>
<br><br><br>
</form>
<div class="col-12 text-center">
<button type="button" name="addInterfacesIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
</div>
</div>
I would like to clone/duplicate the form when the user clicks on the addInterfacesIx button using jQuery I guess.
The jQuery that I am trying looks like this:
<script>
$(document).ready(() => {
$('addInterfacesIx').click(function(){
$('InterfacesIx').clone().insertBefore('addInterfacesIx');
});
});
</script>
When I do console.log($('InterfacesIx')); nothing gets printed out. Is the selector wrong ?
When inspecting the form element on the browser I get:
copy attribute shows name="InterfacesIx"
copy selector path shows #stepper-navigation > li > div.step-new-content.white-text > form
copy xml shows //*[#id="stepper-navigation"]/li/div[2]/form
Would you be so kind to advise what I am doing wrong and how to achieve the desired result ?
Your selector $('addInterfacesIx') is not valid. If you want to grab an element by name you should use attribute selector, something like this: $( "form[name='addInterfacesIx']"). However, as mentioned before, grabbing element by class or ID is definitely better.
$('addInterfacesIx') and $('InterfacesIx') aren't valid selectors. I'd suggest putting id/class attributes on the relevant elements and then selecting them by that.
I also assume that the form elements should be siblings, as such try using insertAfter() and placing the new form after the last one currently in the DOM. Your current logic would place the new form inside the button container. Try this:
jQuery(($) => {
$('#addInterfacesIx').click(function() {
$('.interfacesIx:first').clone().insertAfter('.interfacesIx:last');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="step-new-content white-text">
<p class="text-monospace"><small>helps you rollout a configlet about blahblah</small></p>
<form name="InterfacesIx" class="interfacesIx">
<div class="row">
<div class="md-form col-12">
<input type="text" name="xxx" class="form-control white-text" placeholder="123"><label for="xxx">asn</label>
</div>
<div class="md-form col-12">
<textarea name="yyy" class="md-textarea form-control white-text" rows="3"></textarea><label for="yyy">notes</label>
</div>
</div>
<br><br><br>
</form>
<div class="col-12 text-center">
<button type="button" name="addInterfacesIx" id="addInterfacesIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
</div>
</div>
You are confusing the fact that a name attribute is not normally used as a jQuery selector - the name attribute is normally used for keys to form values when they are submitted to the server. You can select elements using the name attribute, as indicated by the code below, but using id and class attributes is preferred.
<form id="InterfacesIx" name="InterfacesIx">
...
</form>
<div class="col-12 text-center">
<button type="button" id="addInterfacesIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
</div>
<script>
$(document).ready(() => {
$('#addInterfacesIx').click(function(){
// $('#InterfacesIx') is better
$('[name=InterfacesIx]').clone().insertBefore('addInterfacesIx');
});
});
</script>

jQuery Validation Plugin check if "total_cost" is greater than "user_credit" value in fields

I am having hard time understand how jQuery Validation Plugin works with custom method.For all the guides here i found, are either for input form or static values but mine is a bit different.
I have 2 div's like 2 values and one is value of "user_credit" which store how much user have credit. And another is "total_cost" which store total cost of some special options.
The problem and difference that i have and didn't found on any guide is that my "total_cost" is dynamically changed based on previous checkbox values.
Here's part of code from that:
<div class="row">
<div class="col-lg-12">
<label for="link_to_video">Link to video <i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" title="Add link to your product video. Youtube videos will be automatically embedded"></i></label>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="show_video" id="show_video" value="1" data-price="40">
</span>
<input type="text" class="form-control" name="link_to_video" id="link_to_video" placeholder="https://youtube.com/watch?v">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<label for="link_to_product">Link to product <i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" title="Add link to your product"></i></label>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="show_product" id="show_product" value="1" data-price="40">
</span>
<input type="text" class="form-control" name="link_to_product" id="link_to_video" placeholder="http://yourwebsite.com/product-page">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-inline">
<div class="col-lg-12">
<h4>Your credit <span class="label label-default" id="user_credit">2000</span></h4>
</div>
</div>
</div>
<div class="row">
<div class="form-inline">
<div class="col-lg-12">
<h4>Total cost <span class="label label-default" id="total_price">0</span></h4>
</div>
</div>
</div>
And here is part of code that change "total_price" value when some of checkboxes are checked from above.
$inputs=$('#show_product,#show_video').change(function(){
var total=0;
$inputs.filter(':checked').each(function(){
total+= $(this).data('price');
});
$("#total_price").text(total);
});
And another thing is that all guides activate validator in javascript while i activate in form it self
<form action="" name="createListingForm" id="createListingForm" method="POST" role="form" data-toggle="validator" enctype="multipart/form-data">
I have been following documentation from here https://jqueryvalidation.org/documentation/ and searched for alot of guides but no luck in finding solution.
First off, you can not validate the text within a span container. Using this plugin, you can only validate textarea, select, certain types of input elements, and elements with the contenteditable attribute... and they all must be within a form container.
Secondly, if you dynamically change the value of one of these form inputs, you simply call the .valid() method to programmatically trigger validation on this input.
$('#myinput').valid(); // trigger a validation test of #myinput element

Button Click event in Angular JS

I am trying to fire a button click event in angular Js but its not happening at all. Neither i am getting any kind of event related error in developer console of Chrome.
Here is the Markup..
<!-- Login Form Here !-->
<div id="login" ng-controller="LoginformController" style="display: none;" class="col-sm-5 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Login now</h3>
<p>Fill in the form below to get instant access:</p>
</div>
<div class="form-top-right">
<i class="fa fa-pencil"></i>
</div>
<div class="form-top-divider"></div>
</div>
<div class="form-bottom">
<form role="form" action="" method="post" class="registration-form">
<div class="form-group">
<label class="sr-only" for="UserID">User ID</label>
<input type="text" name="UserID" placeholder="User ID..." class="form-first-name form-control" id="UserID">
</div>
<div class="form-group">
<label class="sr-only" for="Password">Password</label>
<input type="text" name="Password" placeholder="Password..." class="form-last-name form-control" id="Password">
</div>
<button type="submit" class="btn">Login!</button>
<br/>
<button type="button" class="btn-sm btn-link" ng-click="PasswordRecovery()">Forgot Password</button>
</form>
</div>
</div>
and here is the anguar JS code..
var app = angular.module('LoginApp', []);
app.controller('LoginformController', function ($scope) {
$scope.PasswordRecovery = function () {
alert("Clicked 2");
}
});
Please help me to resolve this ..
If I would add
<div ng-controller="UnexistingController"></div>
to your HTML then I would get:
"Error: [ng:areq] Argument 'UnexistingController' is not a function,
got undefined
http://errors.angularjs.org/1.4.3/ng/areq?p0=UnexistingController&p1=not%20a%20function%2C%20got%20undefined
Which makes sense, since I did not add a controller to the module yet. I suspect you made the same mistake.
Argument 'SignupformController' is not a f‌​unction, got undefined
Description
AngularJS often asserts that certain values will be present and truthy
using a helper function. If the assertion fails, this error is thrown.
To fix this problem, make sure that the value the assertion expects is
defined and truthy
.
Works for me, I don't understand why you added style="display: none;, but it's not the problem.
See Plunker.

jQuery .on() issue, console.log() works but element interaction doesn't

I am using this code inside $(document).ready(function(){ ... }):
$('#flavours').on('click', '.toggle-quantity', function(e){
e.preventDefault();
var $quantity_percent = $(this).parent().find('.quantity_percent');
if($quantity_percent.is(':hidden')){
console.log("is hidden");
$quantity_percent.show();
}else{
console.log("is not hidden");
$quantity_percent.hide();
}
});
What's happening is the console.log() is working, but the $quantity_percent is not showing/hiding.
Additionally, if I add an alert('test') to the beginning of the function (just after e.preventDefault) this also doesn't work, but the console.log() continues to work (it correctly logs 'is not hidden').
EDIT: Relevant HTML markup:
<div id="flavours">
<div class="row flavour" id="flavour_1" style="display: block;">
<div class="form-group">
<div class="col-xs-12">
<fieldset>
<legend>Flavour 1</legend>
<div class="col-sm-4">
<label>Flavour Name</label>
<input type="text" value="" name="flavour_name[]" data-flavour-id="1" id="flavour_name_1" class="form-control autocomp" placeholder="Flavour name">
<input type="hidden" value="" name="flavour_id[]" id="flavour_id_1" class="form-control flavour_id">
<p class="flavour_info"></p>
</div>
<div class="col-sm-6">
<label>Flavour Quantity <span class="fa fa-filter"></span> <span class="hidden-sm">Switch to </span>drops per ml</label>
<div class="input-group" id="quantity_percent">
<input type="text" class="form-control" id="flavour_percentage_1" name="flavour_percentage[]" placeholder="Flavour Quantity">
<span class="input-group-addon">%</span>
</div>
<div class="input-group" id="quantity_drops" style="display: none;">
<input type="text" class="form-control" id="flavour_drops_1" name="flavour_drops[]" placeholder="Flavour Quantity">
<span class="input-group-addon">drops/ml</span>
</div>
<p class="flavour_recommended_percentage"></p>
</div>
<div class="col-sm-2">
<label> </label>
<button class="btn btn-danger btn-block remove-flavour"><span class="glyphicon glyphicon-remove"></span> Remove</button>
</div>
</fieldset>
</div>
</div>
</div>
$(this).parent() is a label element which doesn't have a child with .quantity_percent
Also quantity_percent is an id and not a class. Use the ID selector
So use
var $quantity_percent = $('#quantity_percent');
instead of
var $quantity_percent = $(this).parent().find('.quantity_percent');
Note: IDs must be unique in HTML
EDIT: as per OPs comments
I updated it to a class rather than ID (as it's on a dynamically growing list)
Usage
var $quantity_percent = $(this).closest('.col-sm-6').find('.quantity_percent');
The .parent() targets the <label> therefore it can't find .quantity_percent

Categories

Resources