I am trying to edit an option of a dropdown and check if the newly edited option is already present in the dropdown.
If it is, it should give an alert, else edit and add the new option in the dropdown.
But there is a case when user clicks edit but then doesn't want to change the name and clicks OK (as that option is in the dropdown it gives alert that the option is already present).
How to check this excluding the option which I am editing?
function IsNameAlreadyPresent(DropdownID,Name){
var Result = false;
$.each($("#"+DropdownID+" option"),function(i,e){
if(e.innerHTML == Name){
Result = true;
return false;
}
});
return Result;
}
function EditOptionName() {
var Name = $("#txtName").val();
if(IsNameAlreadyPresent('DropdownId',Name)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
$('#DropdownId').find(':selected').text($('#txtName').val());
}
}
You want to check first that the user has actually edited the value or selected the previous value only. Store this in a flag variable say 'modified'. Then use the below code:
function EditOptionName() {
var Name = $("#txtName").val();
var modified;
if(IsNameAlreadyPresent('DropdownId',Name) && modified) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
$('#DropdownId').find(':selected').text($('#txtName').val());
}
}
Related
I have a HTML form on an admin site. I need to return all input elements that have one or more input values that are the exact same value. However, the following code is not working. $(this).val() is always returning null for any of the values I enter. However, if I load an existing form with values prefilled, the $(this).val(); works correctly.
if ($('.nickname-input:visible').valid() && $('.funding-input:visible').valid()) {
$('.nickname-input:visible').each(function () {
var nickname = $(this).val();
if ($('input[name="' + nickname + '"]').length == 2) {
showNotification("Error", 'danger', "Account Nicknames must be unique", 'fas fa-exclamation-circle');
return false;
}
});
alert("valid");
}
I was incorrectly targeting the name attribute and not the value attribute.
Resolved Code:
$('.nickname-input').each(function () {
var nickname = $(this).val();
if ($('input[value="' + nickname + '"]').length == 2) {
showNotification("Account Nicknames must be unique", 'danger', "Error", 'fas fa-exclamation-circle');
return false;
}
});
I have a button that triggers a kartik dialog.prompt, where text is put in.
I need the input in the dialog to have several rows and line breaking capability (like textarea)
How to change it from a simple text input to textarea?
Here is my javascript:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt({label:'Text emailu:', placeholder:'Zadejte text emailu'}, function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
I found that if type is not defined (unlike label and placeholder in my case), it defaults to "text". But I wasn't able to make the dialog render any type other than a simple one-row text input.
Apparently, this is not supported in the extension.
Reason:
The reason is that in the dialog.js where the KrajeeDialog.prototype is defined the function bdPrompt is the one that takes care of the prompt dialog that is to be created and it creates the default field type as input rather than deciding on any of the options or parameters passed to KrajeeDialog.prompt() although you can pass a parameter of name type like
krajeeDialog.prompt({
label:'Text emailu:',
placeholder:'Zadejte text emailu',
type:'password'
},function(){})
but this does not decide if the element will be input or textarea type, this parameter type is passed as the attribute of the input element. See the below code block to understand the reason i explained the third line will always create a field of type input.
File yii2-dialog/assets/js/dialog.js Line 110
if (typeof input === "object") {
$inputDiv = $(document.createElement('div'));
$input = $(document.createElement('input'));
if (input['name'] === undefined) {
$input.attr('name', 'krajee-dialog-prompt');
}
if (input['type'] === undefined) {
$input.attr('type', 'text');
}
if (input['class'] === undefined) {
$input.addClass('form-control');
}
$.each(input, function(key, val) {
if (key !== 'label') {
$input.attr(key, val);
}
});
if (input.label !== undefined) {
msg = '<label for="' + $input.attr('name') + '" class="control-label">' + input.label + '</label>';
}
$inputDiv.append($input);
msg += $inputDiv.html();
$input.remove();
$inputDiv.remove();
} else {
msg = input;
}
So you might need to override the javascript function according to your needs if you want to work it that way.
It is possible to add custom html to krajeeDialog.prompt after all.
In the documentation, kartik-v states:
content: string|object: If set as a string, it is treated as a raw HTML content that will be directly displayed.
So if I replace the original object in my code with a string containing the desired html, it will render my textarea or any other form element.
For example, replace it with a textarea html:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt('<textarea>Sample text...</textarea>', function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
Im trying to make an option, for the user to create a list of owned records. However i ran into the following problem:
When the user tries to create a list with no name, an empty/invisible element is added to the list. I want the code, to ask the user to enter a name if he leaves the prompt blank.
When elements are added, i want them to be separate and different elements. Now they are shown and displayed as one.
I hope some of you guys can help me overcome this problem. Please ask if anything seems unclear.
My present code is presented below:
function myFunction1() {
var txt;
var person = prompt("Please enter the name of your record list:");
if (person == null || person == "") {
txt = "";
} else {
txt = person + "<br>";
}
document.getElementById("myRecords").innerHTML += txt;
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
When using prompt, it's best to use a while loop to make sure that input is entered. This will continue cycling the message until the user enters sufficient information. When a user hits cancel a null value is returned. Within the while loop we check if person is null, and if that is the case we immediately return.
To add separate elements you can use document.createElement and then append that element to your selected parent through the use of the appendChild method.
In the below code I took the liberty of converting your myRecords div into a ul or unordered list tag. When names are entered they are added as li ( list item ) children to this tag.
function myFunction1() {
var person, ul = document.getElementById("myRecords"), li = document.createElement("li");
while (!person) {
person = prompt("Please enter the name of your record list:");
if (person == null) return;
}
li.textContent = person;
ul.appendChild(li);
}
myFunction1();
myFunction1();
<ul id="myRecords"></ul>
If you don't want to use a list, you can simply update the markup and change what you are appending. In the below myRecords is an a tag. We append a div with the appropriate text to this anchor tag as we did in the above.
function myFunction1() {
var person, a = document.getElementById("myRecords"), div = document.createElement("div");
while (!person) {
person = prompt("Please enter the name of your record list:");
if (person == null) return;
}
div.textContent = person;
a.appendChild(div);
}
myFunction1();
<a id="myRecords" href="#"></a>
You should use something like an (un)ordered list (<ol>, <ul>) and then append list item (<li>) containing the name in an <a> tag if need be. If you want to append an empty item when a name isn't entered, you don't have to use an if statement.
const getRecordList = () => document.getElementById('recordList');
const getCreateButton = () => document.getElementById('create');
function promptInput(value = '') {
const message = 'Please enter the name of your record list:';
let name = '';
while (name === '') {
name = prompt(message, value);
}
return name;
}
function createListItem(name) {
const listItem = document.createElement('li');
listItem.innerHTML = `<a onclick="updateRecord(this)">${name}</a>`;
return listItem;
}
function createRecord() {
const name = promptInput();
if (!name) return;
getRecordList().appendChild(createListItem(name || ''));
}
function updateRecord(li) {
li.innerHTML = promptInput(li.innerHTML);
}
<h2>Record List</h2>
<ol id="recordList"></ol><hr>
<button id="create" onclick="createRecord()">Create</button>
you need to change your JS to the following:
function myFunction1() {
var txt;
var person = prompt("Please enter the name of your record list:");
if (person == "") {
alert('Please enter a name');
return;
} else if(person == null){
return;
} else {
txt = person;
}
var span = document.createElement('span');
span.setAttribute('class', 'myElement');
span.innerHTML = txt;
document.getElementById("myRecords").appendChild(span);
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
With createElement a new element is created, to add a class you can use setAttribute and then you append it as a child to your myRecords element via appendChild.
function myFunction1() {
let person = prompt("Please enter the name of your record list:");
if (person) {
let div = document.createElement('div');
div.innerText=person;
document.getElementById("myRecords").appendChild(div);
}else{
alert('Please enter a name');
}
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
You can createElement and appendChild to add desired elements.
Without knowing exactly what you're trying to accomplish, this is the solution I came up with for you:
function myFunction(prompt_text) {
var txt;
var list;
var person;
if (prompt_text != '' && prompt_text != undefined) {
person = prompt(prompt_text);
} else {
person = prompt("Please enter the name of your record list:");
}
if (person == null || person == "") {
txt = "";
} else {
txt = '<li>' + person + "</li>";
}
if (txt != '') {
document.getElementById("myRecords").innerHTML += txt;
} else if(person != null){
myFunction("Names cannot be blank, please enter the name of your record list:");
} else {
return;
}
}
<ul id="myRecords"></ul>
<a id="create" onclick="myFunction()">Create RecordList</a>
I've modified the container that you're putting the data into to be an unordered list <ul></ul> to better facilitate having multiple entries in it, and auto-appended the <li></li> DOM so that the list does all of the work for you.
I've also changed the function to accept prompt_text as a parameter, so you can recursively call the function if they don't enter text.
EDIT: updated the code to understand the null returned when a user clicks the cancel button, which removes the error that was created by the code I originally posted.
The final change is the recursive function call I mentioned above. If the txt variable is empty, the function calls itself with new prompt_text allowing you to let the user know WHY they didn't do it right, as well as giving them another opportunity to correct that.
I have an #error paragraph. Everytime there is an error within the form on submit. The inputs placeholder text gets added to the #error paragraph.
My problem:
It happens everytime a user clicks submit. So the #error message returns:
Please fill in yourfirst name, last name, company, position, first
name, last name, company, position, first name, last name, company,
position, first name, last name, company, position, first name, last
name, company, position, first name, last name, company, position,
I've looked for other solutions and tried this:
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
Is there any way to check if the placeholder text already exists in the #error message? Here's a fiddle. I'm sorry it's so convoluted. But its what i've been working on and had it handy.
Thanks for your help in advance!
http://jsfiddle.net/8YgNT/20/
var errorText = '';
//Validate required fields
for (i = 0; i < required.length; i++) {
var input = $('#' + required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
if (input.attr('placeholder').indexOf($('#error')) >= 0) {
// do nothing
} else {
errorText = errorText + $(input).attr('placeholder').toLowerCase() + ', ';
}
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
$('#error').html('').append('Please fill in your ' + errorText);
I simple add one line in your fiddle and it's working now:
required = ["id_first_name", "id_last_name", "id_firmbox", "id_job_title"];
errornotice = $("#error");
emptyerror = "Please fill out this field.";
$("#startform").submit(function(){
//Validate required fields
$("#error").html("Please fill in your");
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
// =====Here===== //
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
// ============== //
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
if ($(":input").hasClass("tobefixed")) {
return false;
} else {
errornotice.hide();
return true;
}
});
$(":input").focus(function(){
if ($(this).hasClass("tobefixed") ) {
$(this).val("");
$(this).removeClass("tobefixed");
}
});
This line do the all trick:
$("#error").html("Please fill in your");
Saludos ;)
If you want to check whether #error contains the string you're wondering about, you can use
($('#error').text().indexOf(a_string)) != -1
This will return true if #error contains a_string.
There's a longer discussion on searching strings for other strings in this question.
It seems you're doing it the wrong way round (and forgetting to get the text out of the #error element):
if ( $('#error').text().indexOf( input.attr('placeholder') ) >= 0)
I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}