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>
Related
I'm working on registration form that has three sections. A user moves to the next section of the form when the button "Next" is clicked. Everything is working well except that validation errors are only showing on the last section of the Form. I would like to validate the form before moving to the next section. For now, when "Next" button is clicked, the user can move to the next section even without filling the fields. I'm not so experienced in JavaScript, please help.
HTML:
<section>
<div class="container">
<form>
<div class="step step-1 active">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="first-name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="last-name">
</div>
<div class="form-group">
<label for="nickName">Nick Name</label>
<input type="text" id="nickName" name="nick-name">
</div>
<button type="button" class="next-btn">Next</button>
</div>
<div class="step step-2">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" name="email">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="number" id="phone" name="phone-number">
</div>
<button type="button" class="previous-btn">Prev</button>
<button type="button" class="next-btn">Next</button>
</div>
<div class="step step-3">
<div class="form-group">
<label for="country">country</label>
<input type="text" id="country" name="country">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" name="city">
</div>
<div class="form-group">
<label for="postCode">Post Code</label>
<input type="text" id="postCode" name="post-code">
</div>
<button type="button" class="previous-btn">Prev</button>
<button type="submit" class="submit-btn">Submit</button>
</div>
</form>
</div>
</section>
JavaScript:
const steps = Array.from(document.querySelectorAll("form .step"));
const nextBtn = document.querySelectorAll("form .next-btn");
const prevBtn = document.querySelectorAll("form .previous-btn");
const form = document.querySelector("form");
nextBtn.forEach((button) => {
button.addEventListener("click", () => {
changeStep("next");
});
});
prevBtn.forEach((button) => {
button.addEventListener("click", () => {
changeStep("prev");
});
});
form.addEventListener("submit", (e) => {
e.preventDefault();
const inputs = [];
form.querySelectorAll("input").forEach((input) => {
const { name, value } = input;
inputs.push({ name, value });
});
console.log(inputs);
form.reset();
});
function changeStep(btn) {
let index = 0;
const active = document.querySelector(".active");
index = steps.indexOf(active);
steps[index].classList.remove("active");
if (btn === "next") {
index++;
} else if (btn === "prev") {
index--;
}
steps[index].classList.add("active");
}
If you want to validate one section of the form before moving on to the next one you should do something like this:
nextBtn.forEach(button => {
button.addEventListener("click", () => {
handleEvent("next")
})
})
prevBtn.forEach(button => {
button.addEventListener("click", () => {
handleEvent("prev")
})
})
where handleEvent is:
function handleEvent(btn) {
if (!handleFormValidation(btn)) return "error message here";
changeStep(btn)
}
Here handleFormValidation would be a function that checks weather the input is correct and returns true if it is and false if it isn't
If you want to make sure the user fills in the first form first before going to the second you can do it by making the second form appear only after the next button is pressed, but that would require a major rework of your system. (i do however advise it because when i copied your code to test it i noticed quite a lot of bugs)
Here are some mdn articles describing how to make, delete and append elements using javascript:
making an element
removing an element
removing an element
appending an element to another element
appending an element to another element
I highly encourage you to do your own research as well.
I also just want to apologise if anything in my answer isn't understandable. I'm new at contributing to this community so there will likely be mistakes I've made.
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.
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.
I'm still relatively new to Vue.js and am having an issue binding one of my inputs to my viewmodel.
Here is my JavaScript:
var viewModel = new Vue({
el: "#InventoryContainer",
data: {
upcCode: "",
component: {
Name: ""
}
},
methods: {
upcEntered: function (e) {
if (this.upcCode.length > 0){
$.ajax({
url: "/Component/GetByUpc",
type: "GET",
data: {
upc: this.upcCode
}
}).done(function (response) {
if (response.exists) {
$("#ComponentInformation").toggleClass("hidden");
this.component = response.component;
} else {
alert("No component found.");
}
});
}
}
}
});
Here is my HTML:
<div class="form-horizontal row">
<div class="col-sm-12">
<div class="form-group">
<label class="control-label col-md-4">UPC Code</label>
<div class="col-md-8">
<input id="ComponentUPC" class="form-control" placeholder="Scan or enter UPC Code" v-on:blur="upcEntered" v-model="upcCode" />
</div>
</div>
<div id="ComponentInformation" class="hidden">
<input type="text" class="form-control" readonly v-model="component.Name" />
</div>
</div>
</div>
Now the issue is that even when I enter a valid UPC code and I assign the component to my ViewModel, the input that is bound to component.Name does not update with the component name. And when I enter into the console viewModel.component.Name I can see that it returns "".
But if I put an alert in my ajax.done function after I've assigned the component and it looks like this alert(this.component.Name) it alerts the name of the component.
Any ideas of where I'm going wrong here?
You cannot use that line
this.component = response.component;
because of the this-variable.
You should put the line
var self = this
before your ajax call and use self.component instead of this.component
in order for vue to work you need to define the parent container with id InventoryContainer
<div id="InventoryContainer" class="form-horizontal row">
<div class="col-sm-12">
<div class="form-group">
....
here is the updated code: https://jsfiddle.net/hdqdmscv/
here is the updated fiddle based on your comment
https://jsfiddle.net/hdqdmscv/2/
(replace this with name of vue variable in ajax)
I have the following code (the html-attributes are for bootstrap-slider):
<!-- Text input-->
<div class="form-group" id = "time">
<label class="col-md-4 control-label" for="notification_time">How many minutes before an event?</label>
<div class="col-md-6">
<input id="notification_time" name="notification_time" type="text" value="{{current_user.notifications_min}}" data-slider-min="5" data-slider-max="120" data-slider-step="5" data-slider-value="{{current_user.notifications_min}}" data-slider-selection="after">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="notifications">E-mail notification</label>
<div class="col-md-4">
<input name="notifications" id="emailnotification" value="emailnotification" type="checkbox" data-on="success" data-off="danger" data-on-label="Yes" data-off-label="No" {% if current_user.daily_mail %} checked {% endif%}>
<span class="help-block">You'll get an email **X** minutes before each event</span>
</div>
</div>
I want X in the above example to automatically change based on the input in notification_time. How do I do this?
Try this:
$('#notification_time').on('change', function () {
var time = $(this).val();
$('.help-block').text('You\'ll get an email ' + time + ' minutes before each event');
});
Edit: note that the change event will only fire when you change and leave the focus of the input. Modern browsers support an input event or you can try using keyup if you wish.
Edit 2: after reading the docs on the slider for bootstrap, try this:
$('#notification_time').slider().on('slideStop', function () {
var time = $('#notification_time').val();
$('.help-block').text('You\'ll get an email ' + time + ' minutes before each event');
});