how to toggle particular field with same id or class? - html

The 'comment' field has 'id' and 'class', I can't give a unique 'id' because it is coming from a database (dynamic output). I have tried to 'toggle' (hide and show) with Jquery, but when I click a particular 'comment' field all of the form (textarea) is appearing (Toggling). How do I toggle a particular field with same id or class?
$(".commentForm").hide();
$(".askForComment").click(function(){
$(".commentForm").toggle();
});
<div id='comments'>
<div id='askForComment' class='askForComment'>Comments?</div>
<div id='viewComments'></div>
<form id='commentForm' class='commentForm'>
<textarea cols='20' rows='2'></textarea>
<input type='button'>
</form>
</div><!-- this element is looped (dynamic) -->

You should target the specific .commentForm here :
$(".askForComment").click(function(){
$(this).siblings(".commentForm").toggle();
});
This will toggle the .commentForm which is near the askForComment. Or, you could do this :
$(".askForComment").click(function(){
$(this).parent().find(".commentForm").toggle();
});
Hope this helps!

Try this
$(".askForComment").on("click",function(){
$(this).next(".commentForm").toggle();
});
As it is the best option rather than click if your HTML formed at runtime means after DOM loding prefer to use $(".askForComment").on("click",function(){

Change this:
$(".askForComment").click(function(){
$(".commentForm").toggle();
});
To this:
$("#comments").on('click', ".askForComment", function(){
$(this).next(".commentForm").toggle();
});
You don't want to use .siblings() because that gets ALL the matching siblings. You want to use .next() because it will only get the closest one.

Related

How to add ID attribute to label with its label name. Label doesn't contain any ID(Ex: id="width-label")

I want to add ID attribute to label using label name. Using jQuery.
<label class="coral-Form-fieldlable">Width</label>
<label class="coral-Form-fieldlabel">Height</label>
<label class="coral-Form-fieldlabel">Quality</label>
<label class="coral-Form-fieldlabel">Color List</label>
In Dom there are multiple class exist with same class name class="coral-Form-fieldable". I want to add ID attribute for only one not all 'label' by using label name = "Width"
It's pretty simple you can use the below code.
$(document).ready(function(){
$(".coral-Form-fieldable").each(function(i,o){
var current=$(this);
current.attr("id",current.text());
console.log(current.attr("id"));
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="coral-Form-fieldable">Width</label>
You Can Try this
also follow this link 100% of your solution
dynamically change label 'for' attribute in with Jquery
$("input, select").each(function(){
var fieldName = $(this).attr('name');
$(this).siblings().attr('for', fieldName);
});
You can try this one
function getElementByValue(selector, value) {
let elements = document.querySelectorAll(selector);
for (let element of elements) {
if (element.innerText.indexOf(value) != -1) {
return element;
}
}
return null;
}
// Call it
getElementByValue(".coral-Form-fieldable","Width")
Add this simple code, you can prefix/suffix the "labelValue" variable while setting the id, because there may be duplicate labels sometimes.
document.querySelectorAll(".coral-Form-fieldable").forEach(function(eachElem){
var labelValue = eachElem.innerText.trim().replace(/\s/g,"_");
eachElem.setAttribute("id",labelValue);
});
<h1 class="coral-Form-fieldable">Element H1</h1>
<p class="coral-Form-fieldable">Element P</p>
<div class="coral-Form-fieldable">Element Div</div>
as others mentioned, you should use attr (for more information please check this link).
you can add id attribute to any element by this part of code:
$('element').attr('id', 'value');
for your problem, you can change the element part with .coral-Form-fieldable but please pay attention, classes return an array. so you have to add a for loop

How to use "invalid-feedback" class with selectpicker from Bootstrap-Select?

I'm using Bootstrap to do some form validation on my web app. With a normal select menu, it would be really easy to have an error message pop-up when the field is invalid:
<select class="someClass" required>
<option value="">Select an option</option>
<option>foo</option>
<option>bar</option>
</select>
<div class="invalid-feedback">Please make a selection.</div>
However, I'm using Bootstrap-Select's "selectpicker" class, and the "invalid-feedback" message in the div no longer works. Is there anyway to force Bootstrap-Select to recognize the "invalid-feedback" class or am I going to have to go about this a different way?
I figured out how to do this, and more generally this is an answer for anytime you have to "manually" force an error to work with Bootstrap's native validation system. It's really hacky, but I couldn't find anything else that works.
Say you have a "selectpicker" that looks like this:
<select id="mySelect" class="selectpicker" required>
<option value="">Select an option</option>
<option>foo</option>
<option>bar</option>
</select>
<div id="error" class="invalid-feedback">Please make a selection.</div>
The error message "Please make a selection" will not show, even if the select element is invalid; it will show, however, if it also has the "d-block" class:
<div id="error" class="invalid-feedback d-block">Please make a selection.</div>
So to manually force errors, you have to use JavaScript to check for the ":invalid" CSS pseudo-class; if it has this pseudo-class, then you add the "d-block" class to your div to show the error. You can use the matches() method and classList.add():
var selector = document.getElementById("mySelect");
var errorMsg = document.getElementById("error");
if(selector.matches(":invalid"))
{
errorMsg.classList.add("d-block");
}
You do this to add the message and you can remove it by checking for ":valid" and removing "d-block" from the classList.
I had multiple versions of the bootstrap-select elements in one of my forms and was having a really hard time getting this to work. The method below won't show the checkmark or x on the input, but it will show the invalid-feedback and valid-feedback boxes properly.
Using the advice from secretagentmango's answer, you can create a function that loops through all of your inputs with the "selectpicker" class, grab their parent form-group element, and then find the children "valid-feedback" and "invalid-feedback" elements
to add or remove the d-block class and hide/show them.
function bsSelectValidation() {
if ($("#myForm").hasClass('was-validated')) {
$(".selectpicker").each(function (i, el) {
if ($(el).is(":invalid")) {
$(el).closest(".form-group").find(".valid-feedback").removeClass("d-block");
$(el).closest(".form-group").find(".invalid-feedback").addClass("d-block");
}
else {
$(el).closest(".form-group").find(".invalid-feedback").removeClass("d-block");
$(el).closest(".form-group").find(".valid-feedback").addClass("d-block");
}
});
}
}
Now you need to run this function after form submit, and you can add it directly to the sample code from the Bootstrap Docs:
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
bsSelectValidation();
}, false);
});
}, false);
})();
The only thing different in the above code from bootstrap's sample is the call to our new function, "bsSelectValidation".
Now you need to listen for changes in the form to automatically update the d-block classes and fix the valid/invalid messages as people make changes to the form:
$('#myForm').change(bsSelectValidation);
Now your select menus should properly show the valid-feedback and invalid-feedback divs on form submit or change.
I found that if I simply remove the value="" part of the "option" element, then the validation message shows properly. That is, if I don't select anything from the dropdown, the my "invalid-feedback" message shows up. When I select something, it goes away and I can proceed further. It's worth a try if you haven't tried it.
My first "option" is simply this: <option>(select)</option> -- no 'value' clause is present.
Hope this helps.

appear an html element by clicking on a button with angularjs

I have an html form ( ) , I want that it is displayed when I click on a button.
the declaration of the form is the following :
<div id = "formulaire" class="gl" >
and the button is :
Edit
I use angularjs in my code . Please help me.
It better to use a simple variable than a function in this case. I would also recommend using controller scope when setting variables instead of the application scope so you don't run into issues with the variables when your application becomes large.
I also picked data-ng-click over ng-click because it will allow the html to validate correctly (which can be checked using the W3's validator).
Try this...
"use strict";
angular.module('myApp', [])
.controller("myController", function() {
this.edit = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div data-ng-app="myApp" data-ng-controller="myController as ctrl">
Edit
<div id="formulaire" class="gl" data-ng-show="ctrl.edit">
<form>
<fieldset>
<label>Field:</label>
<input type="text" />
</fieldset>
</form>
</div>
</div>
Have you looked into the ngShow directive? It ables you to show or hide a DOM element depending on whether the attribute expression resolves to a truthey or falsey value.
Add model change on click
Edit
And then display the form if model is true
<div id = "formulaire" class="gl" ng-if="show">

How to make grey text on a textbox that disapears in MVC

I am searching for the same answer that was given here:
HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?
But I want to do this in MVC4.
I got the following view:
#using (Html.BeginForm("Kompetens", "KumaAdmin"))
{
<div class="three columns" style="margin-right: 627px;">
<h6>Kompetens</h6>
<div style="width:456px;"> #Html.ListBox("kompetensId", (SelectList)ViewBag.KomId)</div><br/>
<h6>Lägg till kompetens</h6>
<div class="focus">
#Html.EditorFor(mm => mm.KompetensTest)
</div>
<input type="submit" style="margin-right: 205px;" value="Skapa"/><br/><br/>
</div>
}
Since this is my textbox:
#Html.EditorFor(mm => mm.KompetensTest)
I don't know how to apply the "onfocus" & onblur attributes on it like in the link above.
You need to create an Editor Template. Because the Html.EditorFor does not have the "object htmlattributes" parameter to do "new { onfocus = "js here" }".
Over the Views>Shared,
Create a folder called EditorTemplates
Then, you create a view using #model string/whathever this object is. Name the file as you want.
When you put the #model on a view you are specifying that it only accepts this type mas a model.
Inside this view, you create a Html.TextBox (not TextBoxFor) and voila.
On the Html.EditorFor method there is also a way to set which editor template you want to use. Choose the one you created by typing its name like this:
#Html.EditorFor(mm => mm.KompetensTest, "GreyedTemplate")
Code for the View I named as: GreyedTemplate.cshtml
#model string
#Html.TextBox("", Model, new { onfocus = "", onclick="" })
Note that the first parameter is empty. This was done on purpose, because when you use EditorFor(mm => mm.KompetensTest,"GreyedTemplate") it uses KompetensTest as the name of the field automatically.
You want to use the placeholder html attribute (http://www.w3schools.com/tags/att_input_placeholder.asp)
Something like #Html.EditorFor(mm => mm.KompetensTest, new { placeholder = "Text" })
#Gmoliv It worked finaly! I googeld arround and found that the "Editfor" does not have access to html attributes. Although I found "TextBoxFor" which has access to them, so the soloution is:
#Html.TextBoxFor(mm => mm.Profile, new { placeholder = "Ange Profil" })
#Pedro I really tried hard to make it work but the problem was that i could not get the value to be set so it was alwasy empty, i treid setting it in the view and in the templateView and it simply did not take. If you could i would appreciate a full code sample
Thanks alot!

Get the value in an input text box

What are the ways to get and render an input value using jQuery?
Here is one:
$(document).ready(function() {
$("#txt_name").keyup(function() {
alert($(this).val());
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<input type="text" id="txt_name" />
//Get
var bla = $('#txt_name').val();
//Set
$('#txt_name').val(bla);
You can only select a value with the following two ways:
// First way to get a value
value = $("#txt_name").val();
// Second way to get a value
value = $("#txt_name").attr('value');
If you want to use straight JavaScript to get the value, here is how:
document.getElementById('txt_name').value
There is one important thing to mention:
$("#txt_name").val();
will return the current real value of a text field, for example if the user typed something there after a page load.
But:
$("#txt_name").attr('value')
will return value from DOM/HTML.
You can get the value attribute directly since you know it's an <input> element, but your current usage of .val() is already the current one.
For the above, just use .value on the DOM element directly, like this:
$(document).ready(function(){
$("#txt_name").keyup(function(){
alert(this.value);
});
});
You have to use various ways to get current value of an input element.
METHOD - 1
If you want to use a simple .val(), try this:
<input type="text" id="txt_name" />
Get values from Input
// use to select with DOM element.
$("input").val();
// use the id to select the element.
$("#txt_name").val();
// use type="text" with input to select the element
$("input:text").val();
Set value to Input
// use to add "text content" to the DOM element.
$("input").val("text content");
// use the id to add "text content" to the element.
$("#txt_name").val("text content");
// use type="text" with input to add "text content" to the element
$("input:text").val("text content");
METHOD - 2
Use .attr() to get the content.
<input type="text" id="txt_name" value="" />
I just add one attribute to the input field. value="" attribute is the one who carry the text content that we entered in input field.
$("input").attr("value");
METHOD - 3
you can use this one directly on your input element.
$("input").keyup(function(){
alert(this.value);
});
I think this function is missed here in previous answers:
.val( function(index, value) )
You can get the value like this:
this['inputname'].value
Where this refers to the form that contains the input.
To get the textbox value, you can use the jQuery val() function.
For example,
$('input:textbox').val() – Get textbox value.
$('input:textbox').val("new text message") – Set the textbox value.
You can simply set the value in text box.
First, you get the value like
var getValue = $('#txt_name').val();
After getting a value set in input like
$('#txt_name').val(getValue);
For those who just like me are newbies in JS and getting undefined instead of text value make sure that your id doesn't contain invalid characters.
Try this. It will work for sure.
var userInput = $('#txt_name').attr('value')
You can try
let quantity = $('input[name = quantity]').val()
where the name of the input field is quantity
Shortest
txt_name.value
txt_name.onkeyup = e=> alert(txt_name.value);
<input type="text" id="txt_name" />