jquery not working with underscore.js - javascript

i am trying to add input boxes on click. but its strange without underscore it is working means input boxes is generating but with underscore.js it is not working.
Also tested with alert("testing"); alert is successfully coming.
<div class="form-group">
<div class="col-sm-10">
<div id="p_scents1">
Add More
<% _.each( type.size, function(i, listItem ){ %>
<%= "<p><label for='p_scents1'><input id='TypeSize"+listItem+"' class='form-control' type='text' placeholder='Please enter Type size' required='required' value='"+i+"' name='data[Type][size]["+listItem+"]'></label></p>" %>
<% }); %>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
var scntDiv = $('#p_scents1');
var i = $('#p_scents1 p').size();
$('#addScnt1').live('click', function() {
alert("testing"); //tested . alert is working fine. but append is not working.
$(scntDiv).append('<p><label for="p_scents1"><input id="TypeSize0" class="form-control" type="text" placeholder="Please enter Type size" required="required" name="data[Type][size]['+i+']"></label> Remove</p>');
i++;
return false;
});
$('#remScnt1').live('click', function() {
if( i > 1 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>

Since those 2 elements are dynamically building, You have to use delegate like this
$(document).on('click', '#addScnt1', function () {
var i = $('#p_scents1 p').size();
$(scntDiv).append('<p><label for="p_scents1"><input id="TypeSize0" class="form-control" type="text" placeholder="Please enter Type size" required="required" name="data[Type][size][' + i + ']"></label> Remove</p>');
i++;
return false;
});
$(document).on('click', '.remScnt1', function () {
var i = $('#p_scents1 p').size();
if (i > 1) {
$(this).parents('p').remove();
i--;
}
return false;
});
Edit
Instead of appending all the elements, troubleshoot the steps by adding elements one by one.
First you can try like this,
$('#p_scents1').append("<span>test</span>");
Then add elements and findout which element causes the problem.

Related

Outsource direct Ajax Script

I have a little html page where I have a field which is for file upload and a input field which is filled by javascript ajax function on same page:
<div class="input-group>
<label>
<span>Select
<input type="file" name="file" style="display: none;">
</span>
</label>
<input type="text" readonly>
</div>
<script>
$(function() {
$(document).on('change', ':file', function()
{
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function()
{
$(':file').on('fileselect', function(event, label)
{
var input = $(this).parents('.input-group').find(':text'),
log = label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
});
});
</script>
I want to move the script from my index.html to my script.js file but it doesn't work. I guess it has something to do with not knowing things like $(document) and so on. I am not a javascript expert and need a little help with this.

If an input has a value, specific radio button should be checked

I want to check if an input (name="companyname") has a value and if so, it should check a radio button (id="Zakelijk"). If it does not have any value, it should check the other radio button (id="Particulier").
See my current code:
<script type="text/javascript">
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport1 = document.getElementById("checkzakelijk");
var dvPassport2 = document.getElementById("checkzakelijk1");
var dvPassport3 = document.getElementById("checkzakelijk2");
var display = chkYes.checked ? "block" : "none";
dvPassport1.style.display = display;
dvPassport2.style.display = display;
dvPassport3.style.display = display;
}
</script>
<div class="col-md-12 check-business">
<div class="form-group form-group-xl">
<label for="Particulier"><input type="radio" id="Particulier"checked="checked" name="checkzakelijk" onclick="ShowHideDiv()" />Particulier</label>
<label for="Zakelijk"><input type="radio" id="Zakelijk" name="checkzakelijk" onclick="ShowHideDiv()" />Bedrijf</label>
</div>
</div>
<div class="col-md-12" id="checkzakelijk" style="display:none;">
<div class="form-group">
<label for="inputCompanyName" class="control-label">{$LANG.clientareacompanyname}</label>
<input type="text" name="companyname" id="inputCompanyName" value="{$clientcompanyname}"{if in_array('companyname', $uneditablefields)} disabled="disabled"{/if} class="form-control" />
</div>
</div>
There are other ways, but this should get you going:
$(function() {
if (($("#inputCompanyName").val() || "") != "")
{
$("#Zakelijk").prop("checked", true)
} else {
$("#Particulier").prop("checked", true)
}
});
This is based on your html where the input name='companyname' also has id 'inputCompanyName' and will clear the other radio because they have the same name=
Edit Working jsfiddle: https://jsfiddle.net/76x42os0/4
change input value in the code box (top left) and click run.
Update: Updated the fiddle to the indicated jquery version 3.1.0 and found the newer version of jquery needs id= to match #, while before it matched on name=
If you want to check it when the input is changed you can do
$("input[name='companyname']").change(function(){
var hasValue = $(this).val() === "";
$("#Zakelijk").prop("checked", hasValue);
$("#Particulier").prop("checked", !hasValue);
})
you can optimize the code, but this is more readable.
In case you need the solution in Javascript
if(document.getElementById("inputCompanyName").value !== ""){
document.getElementById("Zakelijk").checked = true;
document.getElementById("Particulier").checked = false;
}
else{
document.getElementById("Particulier").checked = true;
document.getElementById("Zakelijk").checked = false;
}
Here's a working example of what you're after (albeit without your HTML ids/layout in mind, but you can simply change the IDs within).
$("#text-box").on('change', function(){
if($(this).val() != ""){
$('#rd1').prop("checked", true)
}else{
$('#rd2').prop("checked", true)
}
});
https://jsfiddle.net/bm18hmLa/3/
It hooks into the changed event, so it would occur every time the text-box value has been changed.
After thought:
Changing
$("#text-box").on('change', function(){
to
$("#text-box").on('input', function(){
makes it a little "nicer" in terms of responsiveness.
https://jsfiddle.net/bm18hmLa/5/
and here's a version with your ID names too.
https://jsfiddle.net/bm18hmLa/6/

jQuery when filling form to all required fileds (if empty) add class redBorder except filled

this is my very first question here in stackoverflow, please treat with understanding.
What i've already done
HTML. My form:
<form>
<div>
<label>Surname</label>
<input type="text" class="formInput" value="" name="form[surname]">
</div>
<div>
<label>Name</label>
<input type="text" class="formInput" value="" name="form[name]">
</div>
<div>
<label>Phone</label>
<input type="text" class="formInput swdt phone" value="" name="form[phone]" maxlength="16" autocomplete="off">
</div>
<div>
<label>E-mail</label>
<input type="mail" class="formInput" value="" name="form[email]">
</div>
<div>
<label>City</label>
<input type="text" class="formInput" value="" name="form[city]">
</div>
<div>
<label>Question</label>
<textarea class="formInput w100" value="" name="form[question]" type="text"></textarea>
</div>
<div>
<label>captcha</label><input type="text" class="captchaFld formInput" required="" name="form[verifyCode]">
</div>
<div>
<button class="disabled" id="submit" type="submit" disabled="">send</button>
</div>
</form>
JS. I added an array of required fileds (this is for programmers so they can add all required fileds into this array by themselves) and as long as user has not filled all the fields in array the "send" button is disabled.
var requiredFields = ["surname", "name", "phone", "email", "city", "verifyCode", "question"];
JS. Here is my each function which runs through all elements of the array:
$.each( requiredFields, function( i, l ) {
$(".formInput[name*='form[" + l + "]']").each(function () {
$(this).keyup(function () {
$("#submit").prop("disabled", chkAllFields());
});
});
});
JS. Here is my function chkAllFields() which runs again((( through all elements of the array and check if fields empty or not:
function chkAllFields() {
var valid = false;
$.each( requiredFields, function( i, l ) {
$(".formInput[name*='form[" + l + "]']").each(function () {
if (valid) {
$("#submit").addClass('disabled');
if ($(".formInput[name*='form[" + l + "]']").val() == '') {
$(this).addClass('redBorder');
}
else {
$(this).removeClass('redBorder');
}
return valid;
}
else {
$("#submit").removeClass('disabled');
var input = $.trim($(this).val());
valid = !input;
}
});
});
return valid;
}
What i need for finish
I need to add "redBorder" class to all required and empty fileds (while user types) exept the field which is now filled;
And on "blur" method when user "unfocus" any filed all "redBorder" classes must be removed.
For now it works with mistakes (red borders are strange) and i dont know where to find the fix..
JS Fiddle
Here is my example of code on JSFIDDLE
Thanks in advance.
You should modify your JavaScript to:
$(document).ready(function () {
// get the validation fields
var requiredFields = ["surname", "name", "phone", "email", "city", "verifyCode", "question"];
// use a function because you want to use it 'onkeyup' and on 'focus'
var validate = function(){
$("#submit").prop("disabled", false);
$.each( requiredFields, function( i, l ) {
$(".formInput[name*='form[" + l + "]']").removeClass('redBorder');
if ($(".formInput[name*='form[" + l + "]']").val() == ""){
$("#submit").prop("disabled", true);
$(".formInput[name*='form[" + l + "]']").addClass('redBorder');
}
});
};
// bind the events. I use document in case of you add fields dynamically
$(document).on('keyup', validate);
$('input').focus(validate);
});
Fiddle
http://jsfiddle.net/xzNPh/27/
Have you considered using Jquery Validation plugin?
With this plugin you can easily define which fields are required and also the
conditions/events that have to be met before submiting the form.
Check out this example and see if it suits your project or not.
not totaly sure why you went that complicated route. try this
http://jsfiddle.net/xzNPh/23/
var requiredFields = ["surname", "name", "phone", "email", "city", "verifyCode", "question"];
function checkStatusBtn(){
var valid = true;
$.each( requiredFields, function( i, l ) {
if ($(".formInput[name*='form[" + l + "]']").val()=="") valid=false;
});
// prop is better but im still stuck in an old mindset :(
if (!valid){
$("#submit").attr("disabled", "disabled");
} else {
$("#submit").removeAttr("disabled");
}
}
$(document).ready(function () {
$(document).on("submit","form",function(){
var valid = true;
$.each( requiredFields, function( i, l ) {
if ($(".formInput[name*='form[" + l + "]']").val()=="") valid=false;
});
if (valid) {
// do your form stuff here or leave it blank to submit normaly
} else {
return false;
}
})
$(document).on("blur","input",function(){
checkStatusBtn();
var $this = $(this);
var name = $this.attr("name");
name = name.replace("form[","");
name = name.replace("]","");
$this.removeClass("redBorder");
if (requiredFields.indexOf(name)!==-1){
if ($this.val()==""){
$this.addClass("redBorder")
}
}
});
$(document).on("keyup","input",function(){
checkStatusBtn();
});
checkStatusBtn();
});
personaly i would add a "required" attribute to the fields that are required and just do a check that all inputs that have "required" are filled in. wouldnt use the array route. but you might have a reason for needing it
UPDATED:
is this what you're looking for? => DEMO
$(document).ready(function () {
var requiredFields = ["surname", "phone", "email", "city", "verifyCode", "question"];
$.each( requiredFields, function( i, l ) {
$(".formInput[name*="+l+"]").each(function () {
$(this).keyup(function () {
$("#submit").prop("disabled", chkAllFields());
});
});
});
function chkAllFields() {
$('.formInput').not(this).each(function(){
if($.inArray($(this).attr('name'),requiredFields)>-1 && $(this).val()==''){
$(this).addClass('redBorder');
}
});
var empty=0;
$('.formInput').each(function(){
if($(this).val()==''){
empty++;
}
});
if(empty==0){
$('#submit').prop('disabled',false);
}
else{
$('#submit').prop('disabled',true);
}
}
$('.formInput').blur(function(){
$('.redBorder').removeClass('redBorder');
});
});

Previewing text using Jquery

I am creating a system where a user can preview the title and steps of a recipe, i have created a dynamic form so the user can add more steps, the preview works with the title and first step however it seems that i can't get it to work on the second, third, fourth step. Can anyone help me? Any help would be greatly appreciated!
http://jsfiddle.net/uKgG2/
Jquery
var commentNode = $('#lp-step'),
nameNode = $('#lp-name');
$('input, textarea').bind('blur keyup', function () {
commentNode.html($('textarea[name="step_detail[]"]').val().replace(/\n/g, '<br />'));
nameNode.text('Title: ' + $('input[name="name"]').val());
});
var addDiv1 = $('#addStep');
var i = $('#addStep p').size() + 1;
$('#addNewStep').on('click', function () {
$('<p> <textarea id="step_' + i + '" name="step_detail[]"> </textarea>Remove </p>').appendTo(addDiv1);
i++;
return false;
});
$(document).on('click', '.remNew1', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
HTML
<label for="name">Enter recipe name:</label>
<input type="text" name="name">
<br />
<h1>Method</h1>
<div id="addStep">
<p>
<textarea id="step_1" name="step_detail[]"></textarea>
Add
</p>
</div>
<br />
<button type="submit">
Save on xml
</button>
</form>
<div id="live-preview-display">
<div id="lp-name"> </div>
<div id="lp-step"> </div>
</div>
You should bind the keyup or blur event to all the new textareas which are created with add button or link whatever.
Improved
try this :
$('#addStep').on('keyup', 'textarea', function () {
step_id = $(this).attr('id');
step_text = $('#' + step_id).val();
if($('.'+step_id).length > 0) {
$('.'+step_id).text(step_text);
return;
}
p = document.createElement('p');
p.className = step_id;
$(p).appendTo(commentNode);
$(p).text(step_text);
});
it worked! I saved it to fiddle too. you should just update the recipe name and clean this as I said i't very hacky just have to improve it.good luck. http://jsfiddle.net/uKgG2/3/

adjusting default value script to work with multiple rows

I am using a default value script (jquery.defaultvalue.js) to add default text to various input fields on a form:
<script type='text/javascript'>
jQuery(function($) {
$("#name, #email, #organisation, #position").defaultvalue("Name", "Email", "Organisation", "Position");
});
</script>
The form looks like this:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I am also using a script so that users can dynamically add (clone) rows to the form:
<script>
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
</script>
So, when the page loads there is one row with the default values. The user would then start adding information to the inputs. I am wondering if there is a way of having the default values show up in subsequent rows that are added as well.
You can see the form in action here.
Thanks,
Nick
Just call .defaultValue this once the new row is created. The below assumes the format of the columns is precticable/remains the same.
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
x.find('input:not(:submit)').defaultvalue("Name", "Email", "Organisation", "Position");
return false;
});
You should remove ids from the input fields because once these are cloned, the ids, classes, everything about the elements are cloned. So you'll basically end up with multiple elements in the DOM with the same id -- not good.
A better "set defaults"
Personally I would remove the "set defaults plugin" if it's used purely on the site for this purpose. It can easily be re-created with the below and this is more efficient because it doesn't care about ordering of input elements.
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements)
{
$(inputElements).each(function() {
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true);
}
});
};
Then you can simply do (once page is loaded):
setDefaults(jQuery('form[name=booking] input'));
And once a row is added:
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input')); // <-- let the magic begin
return false;
});
For the toggling of default values you can simply delegate events and with the help of setDefault
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
if ($(this).data('isDefault'))
$(this).val('').removeData('isDefault');
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
Fiddle: http://jsfiddle.net/garreh/zEmhS/3/ (shows correct toggling of default values)
Okey, first of all; ids must be unique so change your ids to classes if you intend to have more then one of them.
and then in your add function before your "return false":
var
inputs = x.getElementsByTagName('input'),
defaults = ["Name", "Email", "Organisation", "Position"];
for(var i in inputs){
if(typeof inputs[i] == 'object'){
$(inputs[i]).defaultvalue(defaults[i]);
}
}

Categories

Resources