Clear input fields on remove jQuery - javascript

I'm using form, where i have remove function. It is working fine but i want the fields value to be clear when remove function triggered. Because i'm also sending input values to my php script.
This is html
<div class="form-group">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Child name</label>
<input class="thevoornaam character" name="voorname[]" type="text" placeholder="Voornaam"/>
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" name="date[]" placeholder="DD / MM / JJJJ" onkeyup="showHint(this.value,'stepname')" />
<!-- <input type="text" size="50" id="URL" onchange="getDoB(this.value)"/> -->
</div>
</div>
</div>
<a class="delete removeButton" href="#" onmouseup="showHint('close','stepname');"><i class="fa fa-times"></i></a>
Here is my js code
(document).ready(function() {
$('#taskForm')
.bootstrapValidator({
framework: 'bootstrap',
fields: {
'task[]': {
// The task is placed inside a .col-xs-6 element
row: '.col-xs-6',
validators: {
notEmpty: {
message: 'The task is required'
}
}
},
'date[]': {
// The due date is placed inside a .col-xs-6 element
row: '.col-xs-6',
validators: {
date: {
format: 'DD/MM/YYYY'
// message: 'Fill valid date of birth'
}
}
}
}
})
.on('added.field.fv', function(e, data) {
if (data.field === 'date[]') {
// The new due date field is just added
// Create a new date picker
data.element
.parent()
// .datepicker({
// format: 'dd/mm/yyyy'
// })
.on('changeDate', function(evt) {
// Revalidate the date field
$('#taskForm').bootstrapValidator('revalidateField', data.element);
});
}
})
// Add button click handler
.on('click', '.addButton', function() {
var $template = $('#taskTemplate'),
$clone = $template
.clone(true,true)
.removeClass('hide')
.removeAttr('id')
.insertBefore($template);
$("#stepname").addClass("disabled")
// Add new fields
// Note that we DO NOT need to pass the set of validators
// because the new field has the same name with the original one
// which its validators are already set
$('#taskForm')
.bootstrapValidator('addField', $clone.find('[name="task[]"]'))
.bootstrapValidator('addField', $clone.find('[name="date[]"]'))
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).closest('.form-group');
// Remove fields
$('#taskForm')
.bootstrapValidator('removeField', $row.find('[name="task[]"]').val(''))
.bootstrapValidator('removeField', $row.find('[name="date[]"]').val(''));
// Remove element containing the fields
$row.remove();
});
});
Here i'm trying to clear the values but it is not working. Can anyone help here what i'm doing miskate?
Thanks is advance

If all you needed to do is a field clear...
I'm iterating around each one with .each and setting its value to an empty string😊
ES6
$('.delete.removeButton').click(() => {
$('.form-group').find('input').each((i, el) => {
$(el).val('')
})
})
ES5
$('.delete.removeButton').click(function () {
$('.form-group').find('input').each(function (i, el) {
$(el).val('')
})
})

use button instead of anchor tag and add onclick= "clearInput()" into it:
<input type="text" id = "clId" class="date" name="date[]" placeholder="DD / MM / JJJJ" onkeyup="showHint(this.value,'stepname')" />
<button onclick= "clearInput()" >clear value</button>
then in js try like this:
function clearInput(){
$('#clId').val('');
}
follow this given way. hope your problem will be sorted out.

Related

count letters/numbers in textarea and show it (without jQuery!)

I'm working with Bootstrap and the CKEditor5 Classic.
I want to have a counter with ONKEYUP in my textarea which should be shown each time the key goes up in div id countThis..
I only need pure javascript I've tried following but it doesnt work..
How can I make it work? thank you!
(I need it without jQuery!)
CODE
<div class="row">
<div class="form-group col-10">
<label class="form-label" for="txt">Ddscription</label>
<textarea id="txt" class="form-control" onkeyup="CheckInput()"></textarea>
</div>
<div class="col-2 mt-4" id="countThis"></div>
</div>
ClassicEditor
.create(document.querySelector('#txt'))
.catch(error => {
console.error(error);
});
function CheckInput() {
var value = document.getElementById("txt").value.length;
console.log(value); // HERE COMES NOTHING
document.getElementById("countThis").innerHTML = value;
}
I suggest to capture the event using CKEditor API instead of the keyup attribute, in this way:
ClassicEditor
.create(document.querySelector('#txt'))
.then(editor => {
/// Register change listener
editor.model.document.on( 'change:data', () => { /// <--- Changes listener
/* ALL THE LOGIC IS DOWN HERE */
document.getElementById("countThis").innerHTML =
editor /// <--- Editor reference
.getData() /// <--- Editor content
.replace(/<[^>]*>/g, '') /// <--- Convert HTML to plain text
.replace(' ', ' ') /// <--- Remove for spaces
.length; /// <--- Get plain text length
});
})
.catch(error => {
console.error(error);
});
<script src="https://cdn.ckeditor.com/ckeditor5/30.0.0/classic/ckeditor.js"></script>
<div class="row">
<div class="form-group col-10">
<label class="form-label" for="txt">Ddscription</label>
<textarea id="txt" class="form-control"></textarea>
</div>
<div class="col-2 mt-4" id="countThis"></div>
</div>

Enable / Disable checkbox depending on value in Kendo-UI dropdown list

I have a Kendo-Ui dropdownlist that is populated with 3 values. If the user selects one of the values I need to enable a checkbox. If either of the other 2 values are selected then the checkbox needs to be disabled.
I am using .Events and e.Select and have created the function but I am not sure where to go next
<div class="row">
<div class="form-group col-sm-3">
<label for="Severity" class="form-label">Severity</label>
#(Html.Kendo().DropDownList()
.Name("SeverityId")
.DataTextField("Name")
.DataValueField("Id")
.OptionLabel("Select Severity...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Get", "Severity", new { area = "Admin" });
});
})
.HtmlAttributes(new {style = "width: 100%"})
.Events(e =>
{
e.Select("onSeverityChange");
})
)
</div>
<div class="form-group col-sm-1">
<input type="checkbox" class="form-control k-checkbox" id="checkboxFatal" disabled="disabled" />
<label class="k-checkbox-label" for="checkboxFatal">Fatal</label>
</div>
<script>
function onSeverityChange(e) {
if (e.dataItem.Name) {
$("#Fatal").enabled = true;
} else {
}
}
</script>
I believe your logic is correct, but the problem is how you're trying to enable/disabled the element. Try:
$("#checkboxFatal").attr("disabled", true);
First, the real id of the element is checkboxFatal and not Fatal. Then you need to use attr() to change any attribute value in jQuery.

Parsley validation on button + custom validator not working

I have a form, styled with bootstrap, that contains multiple fields (tel number, date, start time, end time...), meant to book bicycles.
When those fields are changed, a script checks throught ajax if a bicycle is free and change the class of a button (act as submit by default) from .btn-danger (red - no bicycle available) to .btn-success (green - You got one !) accordingly :
<form id='resa_velo_form' name='resa_velo_form' method='POST' action='index.php?app=resa&ctrl=AccueilUserCtrl&action=enregistreResaVelo'>
<div class='form-group col-md-3'>
<label for="velo_date">Date d'emprunt : </label>
<div class='input-group date' id='datetimepicker_deb'>
<input type="text" id="velo_date" name="date_start" autocomplete="off" class="form-control" required>
<span class="input-group-addon">
<span class=" fa fa-calendar"></span>
</span>
</div>
</div>
<div class='form-group col-md-2'>
<label for="velo_time_start">DĂ©part :</label>
<input id="velo_time_start" class="timepicker_input velo spinner" name="time_start" value="8:30" required>
</div>
<div class='form-group col-md-2'>
<label for="velo_time_end">Retour : </label>
<input id="velo_time_end" class="timepicker_input velo spinner" name="time_end" value="9:30" data-parsley-timeissup="#velo_time_start" required>
</div>
<div class='form-group col-md-5'>
<label> </label>
<button id="disponibilite_velo" class="error_resa btn btn-danger col-md-12" data-parsley-success='btn-success' required>Choisissez une date</button>
</div>
</form>
I managed to use Parsley to validate this form and even got to apply .has-error classes to form-group :
$('#resa_velo_form').parsley({
successClass: "has-success",
errorClass: "has-error",
classHandler: function(el) {
return el.$element.closest(".form-group");
}
})
I'm using successfully a custom validator on start and end time :
window.Parsley.setLocale('fr');
window.Parsley.addValidator('timeissup', {
requirementType: 'string',
validateString: function(value, requirement) {
time1 = $(requirement).val().split(/:/);
time1 = time1[0] * 3600 + time1[1] * 60;
time2 = value.split(/:/);
time2 = time2[0] * 3600 + time2[1] * 60;
return (time2 > time1);
},
messages: {
en: 'This value should be higher than start time.',
fr: "Cette valeur doit ĂȘtre supĂ©rieure Ă  l'heure de dĂ©part."
}
});
BUT THEN...
I tried to make a custom validator to check the class of the button :
window.ParsleyConfig = {
excluded: 'input[type=hidden], :hidden, input[type=reset]',
inputs: 'input, textarea, select, input[type=button], button, input[type=submit]'
};
window.Parsley.addValidator('success', {
requirementType: 'string',
validateString: function(value, requirement) {
console.log('ok - Parlsey Valid Success');
return ($('#disponibilite_velo').hasClass(requirement));
},
messages: {
en: 'This button should be green !',
fr: "Ce bouton doit ĂȘtre vert !"
}
});
And it never works, Parlsey doesn't seems to use this validator, but still checks fields required and "timeissup" custom validator.
In fact, I managed to make it work by attaching it to an input field, but that's not the point.
Any help, please ?
Got it to work !
Contrary to this answer, you need to define excluded and inputs in the form validator itself :
$('#resa_velo_form').parsley({
successClass: "has-success",
errorClass: "has-error",
excluded: 'input[type=reset]',
inputs: 'input, textarea, select, button',
classHandler: function(el) {
return el.$element.closest(".form-group");
}
});
Other important thing : even if it's a button, you need the required attribute and a value different from '' (empty):
<button id="disponibilite_velo" class="error_resa btn btn-danger col-md-12" data-parsley-inputsuccess='btn-success' value='*' required>Choisissez une date</button>
Maybe not so clean, but... working !

how to trigger same name class only on current input text box in jquery plugin?

hello i am creating ajax search plugin.I have created some dynamically div. suppose I have two input box field and the div which is dynamically generated have same name . So I want to project only that div in which user enter the value on text box not other, but it fetch result on both div whether I type on first or second input box.
HTML
<div class="row" style="padding:10px">
<div class="col-md-6">
<input type="text" class="form-control" name="" value="" id="searchText1">
</div>
<div class="col-md-6">
<input type="text" class="form-control" name="" value="" id="searchText2">
</div>
</div>
js file
$(document).ready(function(){
$('#searchText1').typefast({
hint:true,
autocomplete:true,
});
$('#searchText2').typefast({
hint:true,
autocomplete:true,
});
jquery plugin file
var timeOut = null;
var $current;
var $info;
var input;
var hint;
var comment;
(function( $ ) {
$.fn.typefast = function(a){
$(this).one('keydown',function(){
input=$(this);
$('body').bodyAppend($(this));
$(this).css({
'position': 'relative',
'top': '-34px',
'background': 'transparent',
'padding-left': '11px',
'font-size': '16px'
})
$('<div>').attr({
name: 'comment',
class: 'comment'
}).insertAfter($(this));
comment=$(this);
})
$(this).on('keydown',function (e) {
var _this = $(this);
clearTimeout(timeOut);
timeOut = setTimeout(function() {
var m = _this.val();
api.searchResult(m,e);
// console.log(ui.input);
console.log(m);
},500);
})
$.fn.bodyAppend=function(m) {
$(window).ready(function() {
$('<input>').attr({
type: 'text',
name: 'input1',
class: 'form-control',
id:'result',
placeholder: 'working'
}).insertBefore(m);
hint=$('#result')
single=$('.single')
})
}
};
}( jQuery ));
My Question is that irrespective of number of input text field on page. My comment should point only the current input box in which I am on working. It should not update the other comment field
class single is the field in which ajax request result displayed.
What is the best way of doing this??
For this case you can set one common class to all input field and apply typefast function on focus event to that class.
For Example,
HTML code
<div class="col-md-6">
<input type="text" class="form-control searchtext" name="" value="" >
</div>
<div class="col-md-6">
<input type="text" class="form-control searchtext" name="" value="" >
</div>
Javascript Code,
$(document).ready(function () {
$(document).on("focus", ".searchtext", function () {
$($(this)).typefast({
hint: true,
autocomplete: true,
});
});
});

Vue-js removed selected date from textbox when add new element

Vue-js remove selected date from textbox when add new element. if i entered any text instead of date and add new element text is display as is it. but date is removed.
below is my HTML code
<div class="dateAvailabilityContainer">
<div class="dateAvailability" v-for="(date, index) in dates">
<div class="form-group date">
<input type="text" v-model='date.date' class="form-control date" v-bind:class="'datepicker_'+index" placeholder="Date">
</div>
<div class="form-group">
<input type="text" v-model='date.from' class="form-control from" placeholder="From">
</div>
<div class="form-group">
<input type="text" v-model='date.to' class="form-control to" placeholder="To">
</div>
<a href="#" v-if="index == 0" class="btn btn-success" v-on:click="addNewDate">
<i class="fa fa-plus"></i>
</a>
<a href="#" v-if="index > 0" class="btn btn-danger" v-on:click="removeThisDate(index)">
<i class="fa fa-minus"></i>
</a>
</div>
</div>
and below is my vue-js code
var addAvailability = new Vue({
el: '#addAvailability',
data: {
dates : [{
date : '',
from : '',
to : '',
}],
},
mounted: function () {
this.addDatePicker( this.dates.length - 1 );
},
methods: {
addNewDate: function () {
this.dates.push({
date: '',
from: '',
to: '',
});
this.addDatePicker( this.dates.length - 1 );
},
removeThisDate : function(index){
this.dates.splice(index, 1);
},
addDatePicker : function( id ){
setTimeout(function(){
console.log('.datepicker_'+id);
$('.datepicker_'+id).datepicker({
autoclose: true,
});
},500);
}
}
});
please help where i create a mistake.
please check in fiddle : https://jsfiddle.net/renishkhunt/bod4ob5y/19/
Thanks
Bootstrap (js) and jquery aren't friendly working with vue.
I think that it is because they modify DOM directly while vue also has a virtual DOM and works in a more data driven way.
Make them work together requires extra logic, I could only fix datetimepicker, I never haven't work with clockpicker before
First I change addNewDate function
//Save new date in a variable
var dateModel = {
date: '',
from: '',
to: '',
};
this.dates.push(dateModel);
var elementId = "datepicker_"+(this.dates.length - 1);
//pass new date to initDate function
this.initDate( elementId, dateModel );
In initDate we need to listen for date changes and update model
$('#'+id).datepicker({
...
}).on('changeDate', function(e){
dateModel.date = e.format();
});
Please see this partially working fiddle
As alternative you could use vue-flatpickr, at this moment is the best "vue's way" that I have found to handle date time inputs

Categories