I am getting the below json response from an validation api , the first attribute is the id of each input field with the error message.
{
"backgroundcolor": "Color is not Supported",
"terms" : "Sorry the Terms are blank"
}
I am using jquery and bootstrap and want to append the below html just after each input field of that specific id . Is this possible to add div dynamically ?
<div id="backgroundcolor" class="invalid-feedback">
Color is not Supported
</div>
Before :
<div class="col-md-6">
<input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
</div>
After :
<div class="col-md-6">
<input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
<div id="backgroundcolorFeedBack" class="invalid-feedback">
Color is not Supported.
</div>
JavaScript alone is the best and fastest solution, so here it is how i would do it:
let response = JSON.parse(response);
let fragment = document.createDocumentFragment()
let child = document.createElement('div');
child.id = Object.keys(response)[0] + 'FeedBack';
child.className = 'invalid-feedback';
child.innerText = Object.values(response)[0];
fragment.appendChild(child);
document.getElementById(Object.keys(response)[0]).after(fragment);
I hope it'll help.
Note: createDocumentFragment() may be slightly faster than createElement alone, but it's not required.
Edit: you can also check if there is already div with that error, it would prevent duplication of divs
if(!document.getElementById(Object.keys(response)[0].length) {
// Here goes code from above
}
Related
I have added this checkbox to my form:
<div class="row">
<div class="form-group col">
<input type="checkbox" name="prd_presell" id="product_presell"
onclick="presellTXT()" value="TRUE" #if(!empty($product)) #if($product->prd_presell == 'TRUE') checked #endif #endif>
<label for="presell_product">Presell Product</label>
</div>
</div>
So there is an onClick function named presellTXT() which goes like this:
function presellTXT() {
var presell_checkbox = document.getElementById("product_presell"); // get checkbox
var presell_text = document.getElementById("show_presell_text"); // text div
var presell_text_input = document.getElementById("presell_product_text"); // text input
if (presell_checkbox.checked == true){
presell_text.style.display = "block";
} else {
presell_text_input.value = "";
presell_checkbox.value = "";
presell_text.style.display = "none";
}
}
So when the checkbox is checked, it basically shows the element with an id of show_presell_text:
<div class="row" id="show_presell_text">
<div class="col-lg-12">
<div class="form-group">
<label>Product Presell Text:</label>
<input name="prd_presell_text" id="presell_product_text" class="form-control" value="{{ old('prd_presell_text', !empty($product) ? $product->prd_presell_text : '') }}">
</div>
</div>
</div>
So when the page loads, it should not be showing the Product Presell Text unless the checkbox is checked.
Now if you take a look at jsfillde example, you can see as soon as the page loads, the text input appears however the checkbox is not checked at all!
So how to hide the text input when the page loads and the checkbox is not checked?
Note: I don't want to use CSS for this because I need to determine correctly if prd_presell is checked on page loads (because of #if($product->prd_presell == 'TRUE') which retrieves data from the DB) then it has to show the Product Presell Text text input.
UPDATE:
I tried adding this:
#show-presell-text.hidden {
display: none !important;
}
And adding this to the div:
<div class="row" id="show_presell_text" class="#if(!empty($product)) #if($product->prd_presell != 'TRUE') hidden #endif #endif">
But does not work and hide the element.
to hide/show the elements on load then this can be easily done by adding an if statement like so
#if (!empty($product))
<div class="row" id="show_presell_text">
<div class="col-lg-12">
<div class="form-group">
<label>Product Presell Text:</label>
<input name="prd_presell_text" id="presell_product_text" class="form-control" value="{{ old('prd_presell_text', !empty($product) ? $product->prd_presell_text : '') }}">
</div>
</div>
</div>
#endif
This will completely omit the element you want at page load if empty and you can add it via JS code. However, If you want to just hide it using CSS classes you can do this:
<div class="row" id="show_presell_text" class="#if (empty($product)) hidden #endif">
<div class="col-lg-12">
<div class="form-group">
<label>Product Presell Text:</label>
<input name="prd_presell_text" id="presell_product_text" class="form-control" value="{{ old('prd_presell_text', !empty($product) ? $product->prd_presell_text : '') }}">
</div>
</div>
</div>
If the product is empty the class will not be present and you can use CSS to set the element to display: none if the class is absent. Let me know if I can clarify further or if I got something wrong.
Edit: A better alternative for the second code block would be to add a hidden class as suggested below if the product is empty and then use it to hide it via CSS. You can then simply add or remove this class via JS as needed.
#show-presell-text.hidden {
display: none;
}
You can try out something like this.
<div class="row" id="show_presell_text" style="display: none">
By default set the display as none and based on the condition in function set it as block/ none.
This is the code. I am using bootstrap valid and invalid classes to change input design once the length is valid and adding a feedback message.
When I run it the function doesn't work and the input field stays the same!
var name = document.getElementById("name");
var validFB = document.getELementById("valid-feedback");
var invalidFB = document.getElementById("invalid-feeback");
name.onblur = function lengthCheck() {
if (name.length > 1 && name.length < 20) {
name.classList.remove("form-control");
name.classList.add("form-control is-valid")
validFB.style.display = "block";
} else {
name.classList.remove("form-control");
name.classList.add("form-control is-invalid");
invalidFB.style.display = "block";
}
}
<div class="col-md-4">
<label for="validationServer01" class="form-label">First name</label>
<input type="text" class="form-control" id="name" required>
<div class="valid-feedback" style="display:none;">
Looks good!
</div>
<div class="invalid-feedback" style="display:none;">
Length should not exceed 50 characters.
</div>
</div>
<div class="col-md-4">
<label for="validationServer02" class="form-label">Last name</label>
<input type="text" class="form-control" id="name" required>
<div class="valid-feedback" style="display:none;">
Looks good!
</div>
<div class="invalid-feedback" style="display:none;">
Length should not exceed 50 characters.
</div>
</div>
There were multiple errors in your post.
Bad syntax
First, you were once using document.getELementById(..) instead of document.getElementById(..) (there was one upper L which cause syntax error)
You should read the documentation to better understand syntax and how it works.
Multiples Ids
In your code you were using the same ID value for multiple elements which may cause collision in the future.
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique class of objects
I encourage you using different IDs for all of your HTML tags.
Input value
To check the input length, you were using name.length but, here name is an HTML element and not a string as you were expected.
To retrieve the value of an input you should use name.value and then use name.value.length to check the value.
Adding class names
You were trying to add multiple class names at once with classList.add(..) which cause the following error :
Failed to execute 'add' on 'DOMTokenList': The token provided ('class1 class2') contains HTML space characters, which are not valid in tokens.
Conclusion
Your snippets contains multiple error that you better handle one at the time. You should open you console when you're coding (with ctrl+f12) and check the error while you are coding.
EDIT
I also change name.onblur to name.addEventListener('blur',...) which is more easy to use in my opinion. You can check the documentation here !
let name = document.getElementById("firstName")
let invalidFB = document.getElementById("invalid-feedback-first-name")
let validFB = document.getElementById("valid-feedback-first-name")
name.addEventListener("blur",function(){
if (name.value.length > 1 && name.value.length < 20) {
name.classList.add("form-control");
name.classList.add("is-valid")
validFB.style.display = "block";
invalidFB.style.display = "none";
} else {
name.classList.remove("form-control");
name.classList.add("form-control");
name.classList.add("is-invalid")
invalidFB.style.display = "block";
validFB.style.display = "none";
}
})
<div class="col-md-4">
<label for="validationServer01" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
<div class="valid-feedback" style="display:none;" id="valid-feedback-first-name">
Looks good!
</div>
<div class="invalid-feedback" style="display:none;" id="invalid-feedback-first-name">
Length should not exceed 50 characters.
</div>
</div>
<div class="col-md-4">
<label for="validationServer02" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" required>
<div class="valid-feedback" style="display:none;">
Looks good!
</div>
<div class="invalid-feedback" style="display:none;">
Length should not exceed 50 characters.
</div>
</div>
I have a javascript function that takes a value from a select and append its to the end of a textarea field (mask) whenever a new selection is made from the select
function addToEditMask(select, mask)
{
var selectedValue = document.getElementById(select).value;
document.getElementById(mask).append(" + "+selectedValue);
}
This function is used by two different elements on the same page as follows:
<div class="form-group">
<label for="edit_filename_mask_mask" id="edit_filename_mask_masklabel">
Mask
</label>
<textarea type="text" id="edit_filename_mask_mask" name="edit_filename_mask_mask"
aria-describedby="edit_filename_mask_masklabel" class="form-control" rows="10" cols="80"></textarea>
</div>
<div class="form-group">
<label for="editMaskVarList" id="editMaskVarListlabel">
Mask Fields
</label>
<select class="mb-2 form-control custom-select" id="editMaskVarList" onchange="addToEditMask('editMaskVarList', 'edit_filename_mask_mask');">
<option>
acoustic (Acoustic)
</option>
.....
and
<div class="form-group">
<label for="add_filename_mask_mask" id="add_filename_mask_masklabel">
Mask
</label>
<textarea type="text" id="add_filename_mask_mask" name="add_filename_mask_mask"
aria-describedby="add_filename_mask_masklabel" class="form-control" rows="10" cols="80"></textarea>
</div>
<div class="form-group">
<label for="addMaskVarList" id="addMaskVarListlabel">
Mask Fields
</label>
<select class="mb-2 form-control custom-select" id="addMaskVarList" onchange="addToEditMask('addMaskVarList', 'add_filename_mask_mask');">
<option>
acoustic (Acoustic)
</option>
......
In each case the select and the mask are both within a Bootstrap modal dialog. But it only works for the second case (add_filename_mask_mask) not the first case (edit_filename_mask_mask)
I added some debugging to ensure
function addToEditMask(select, mask)
{
var selectedValue = document.getElementById(select).value;
document.getElementById(mask).append(" + "+selectedValue);
alert('Adding to mask:'+mask+':'+scriptvar+':'+document.getElementById(mask).value);
}
that the function was actually being called in both cases and all the variables a renamed correctly. Yet although there are no webconsole errors and the append() method doesnt report any error the value of mask doesnt change for edit_filename_mask_mask
I cannot create a SSCE since there seems to be no difference between the working and non working version. The only difference of note is that when modal dialog is first displayed edit_filename_mask_mask has a value but add_filename_mask_mask does not. However edit_filename_mask_mask continues to fail if I blank out edit_filename_mask_mask , and add_filename_mask_mask when has value.
What happens if you try some safety checks ?
function addToEditMask(select, mask)
{
var selectedValue = document.getElementById(select).value || "";
var textarea = document.getElementById(mask);
textarea.value = (textarea.value || "") + " + " + selectedValue;
}
Variable name is "selectedValue" and you call to "selectValue"
In my app I have multiple divs which look like (The divs are created dynamically):
<div class="form-group clearfix">
<div class="form-group first-name">
<input type="text" id="firstName0" class="signup-input firstName required" name="first[0]" placeholder="">
</div>
<div class="form-group last-name">
<input type="text" id="lastName0" class="signup-input lastName" name="last[0]" placeholder="optional">
</div>
<div class="form-group email">
<input type="text" data-index="0" id="inputMail0" class="signup-input mail" name="email[0]" placeholder="e.g. example#url.com" aria-invalid="true">
<span class="common-sprite sign-up-cross first"></span>
</div>
</div>
The names are dynamically generated according to the index (For example the are email[1], email[2].....).
I have a button which should be disabled in case the field of the first name is not empty and the field of the email is empty and the span hasn't a class of disNone.
How should I disable the button according to above condition?
If I understand you correctly, you want to disable the button if all of the following conditions are met:-
First name field is NOT empty - $('#firstName0').val() != ''
Email field IS empty - $('#inputMail0').val() == ''
Span does NOT have class of disNone - !$('span').hasClass('disNone')
So I would check that condition this way by wrapping it in a listener on the keyup event upon the form:
$('.form-group').on('keyup', function () {
console.log('keyup');
if ($('#firstName0').val() !== '' && $('#inputMail0').val() === '' && !$('.email span').hasClass('disNone')) {
//Now do whatever with your button.
$('.mybutton').prop('disabled', true);
} else {
$('.mybutton').prop('disabled', false);
}
});
Demo: http://jsfiddle.net/ajj87Lg3/
Hope this condition works out for you.
Store the jQuery objects in variables and use that variables instead, which is a much better way to do it.
$(function(){
var firstName = $('#firstName0').val();
var inputMail = $('#inputMail0').val();
var checkClass = $('span').hasClass('disNone');
if( firstName!=='' && inputMail==='' && !checkClass ) {
$('button').attr('disabled','disabled'); //in the fiddle you would see an alert, you just have to replace that code with this one
}
});
EDIT: If your DIVS are being generated dynamically you can use the each() jquery function to loop through them.
$(function(){
$('#mainDiv').children('div').each(function(index,element){
var nameDiv = $(element).find(":nth-child(1)");
var firstName = $(nameDiv).find('input').val();
var emailDiv = $(element).find(":nth-child(3)");
var inputMail = $(emailDiv).find('input').val();
var spanElem = $(emailDiv).find("span");
var checkClass = $(spanElem).hasClass('disNone');
if(firstName!=='' && inputMail==='' && !checkClass){
$('button').attr('disabled','disabled');
//in the fiddle you would see a console.log('hi'), you just have to replace that code with this one for whatever button you want to disable
}
});
});
Checkout the FIDDLE LINK
In the fiddle I have left out one SPAN tag with class disNone and other SPAN tag without class disNone. So only once the condition executes
Right now I have my form set up with a generic button. Would it be easier to use a submit?
I'm trying to capture the user input and then pass it on as part of a URL. Using .find has been getting me an array of something else.
div class="username-input form-horizontal">
<!-- <div class="form-group"> -->
<label for="inputUsername" class="col-sm-3 control-label">Username</label>
<div class="col-sm-5">
<input type="text" value="Username" id="inputUsername">
</div>
</div>
<button class="signup-button col-sm-1 control-label"> Sign in </button>
<script>
$(document).ready(function() {
$(".signup-button").click(function() {
var usernameInput = $('form').find('input[type=text]')
console.log(usernameInput)
});
});
You're accessing the element not the value. Use val for it
var usernameInput = $('form').find('input[type=text]').val(); // now you get input
Since you have input field ID & it should be unique so you can use ID as selector also.
var name = $("#inputUsername").val();
You have to access value. This is the way you can access value of input text.
$(document).ready(function() {
$(".signup-button").click(function() {
var usernameInput = $('#inputUsername').val();
console.log(usernameInput);
});
});