Javascript Hide-Unhide HTML Text Box - javascript

I want to hide & un-hide html text box when selecting another select value using JavaScript.
$(document).on('change', '#pf_status', function() {
var val = $(this).val();
console.log(val);
if (val == 2) {
$('#ref-col').hide();
} else {
$('#ref-col').show();
}
});
$(document).ready(function() {
$('#ref-col').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group">
<label>
Pass Fail Status <span class="text-danger">*</span>
</label>
<select class="form-control" name="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group">
<label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>
I did not get the desired output. I think something going wrong. Can any one help me ?

Spelling the selector the same as the ID
ID not name is used in the script
No need to delegate if not dynamic
Dropdown does not have a "please select" so trigger the change on load of the page
$(function() {
$('#pf_status').on('change',function() {
var val = $(this).val();
$('#ref_col').toggle(val != 2);
}).trigger("change"); // trigger to handle the lack of "Please select"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group">
<label>
Pass Fail Status <span class="text-danger">*</span>
</label>
<select class="form-control" id="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group">
<label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>

This is an issue with your selector you are selecting the drop-down with a name using a # sign:
and there's also a problem with your selector #ref-col in your JS it should be like this #ref_col
change your name to id="pf_status" in your HTML like this and this will work:
$(document).on('change', '#pf_status', function() {
var val = $(this).val();
$('#ref_col').toggle(val!=2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group">
<label>
Pass Fail Status
<span class="text-danger">*</span>
</label>
<select class="form-control" id="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group">
<label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>

You should always try to figure out why the code it is not working.
Always check your browser console, There you will get errors with line numbers.
This way you will learn to master coding with time.
And don't worry about negative rating for your question.WE are developers to push ourselves to create, develop and design for the betterment of the world.
JQUERY:
$(document).on('change','#pf_status',function(){
// Here you are using this object to refer to something that is not available in DOM.
});
In your HTML, use id attribute for the select element.And this will work fine.
Well that is already shown above.I will show you how to setAttribute in javascript for your code without changing any code in your HTML.So that you learn.
In Javascript:
let ps = document.getElementsByName('pf_status');
ps[0].setAttribute("id","pf_status"); // if you have only 1 select element in your document
There surely are other issues in your code that are all sorted out by other developers.

You are using ID selector in your JQuery and declared as name attribute in your form
<select class="form-control" name="pf_status">
either change it to <select class="form-control" id="pf_status">
or
Use the name selector $(document).on('change', 'select[name="pf_status"]' in JQuery selector.
$(document).on('change', '#pf_status', function() {
var val = $(this).val();
console.log(val);
$('#ref_col').toggle(val!= 2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group"><label>Pass Fail Status <span
class="text-danger">*</span></label>
<select class="form-control" id="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group"><label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>

Related

Error duplicating Div with Select2 library

I am trying to clone a div, which contains some input, and one of those is the Select2 library, when cloning it clones me but the library does not work.
attached bug: "Uncaught TypeError: Cannot set properties of null (setting 'outerHTML')".
This is my html code.
<div class="cloned" style="width: 100%;">
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="txtinput0" name="username" placeholder="Enter Full Name" type="text" data-parsley-pattern="^[a-zA-Z\s.]+$" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="txtinput0" name="email" placeholder="Enter VALID EMAIL and check the result" type="email" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="txtinput0" name="phone" placeholder="Enter Phone e.g.: +363012345" type="text" data-parsley-pattern="^\+{1}[0-9]+$"/>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<select class="chosen-select" multiple="multiple" style="width: 100%;" id="select0" data-placeholder="Select a company" >
<div clas="options">
<option value="1">Google</option>
<option value="1">Amazon</option>
<option value="1">Facebook</option>
<option value="1">Airbnb</option>
</div>
</select>
</div>
</div>
</div>
</div>
<div clas="row box" id="clone"></div>
And this is the javascript with which I try to clone the whole div, including the select2
$(document).ready(function() {
$('#select0').select2();
});
var i=1;
var prev =0;
function addRow() {
var clone = $("#row_examenes").clone()
clone.find("#txtinput"+prev).attr("id", "txtinput"+i);
clone.find("#select"+prev).attr("id", "select"+i);
clone.find("#select"+prev+"_chosen").attr("id", "select"+i+"_chosen1");
clone.appendTo($("#clone"));
document.getElementById("select"+i+"_chosen1").outerHTML=""
$myid = $('#select' + i);
$myid.show().select2();
i++;
prev++;
}
There are quite a few problems in the code, but the big issue is:
When you initialise a Select2, it hides the original <select> and adds some extra HTML on the page. If you then clone the block of HTML where that Select2 is, you clone all that extra Select2 stuff. And if you then try an initialise that cloned stuff as a Select2, it won't work.
The fix is described in many duplicate questions here on SO already (try searching for "select2 clone"), here's an example: you need to destroy the original Select2 before cloning it, and then re-initialise it as a Select2 again once it is cloned;
Some of the other issues in the code are:
There is no element with id row_examenes. I added it as a <div> enclosing the <div class="cloned">;
Once you clone that div, the clone will have the same ID (row_examenes), and the code does not change that ... duplicate IDs are invalid HTML. Instead we can clone the <div> nested inside, with class cloned;
All 3x text <input>s have the same ID, txtinput0 - this is invalid, and jQuery will only be able to find the first one. I changed them to name0, email0, and phone0;
The HTML has an unbalanced </div>, the opening <div> I added fixes that too;
After the clone is created, and before the IDs are updated, it includes elements with non-unique IDs. It isn't actually in the DOM yet, and you are using clone.find() to scope your search to find them, so probably that's OK ...? But it seems unnecessarily risky, when we don't have to do it that way - why not play it safe, and search for the inputs instead of the IDs;
<div clas="row box" id="clone"></div> - typo in class;
There was no way to trigger addRow() so I added a simple button, and a click handler for it;
Here's a working, simplified snippet with those issues fixed:
$(document).ready(function () {
$('#select0').select2();
$('button').on('click', addRow);
});
// How many clones on the page?
let clones = 0;
function addRow() {
// We've added a clone
clones++;
// First need to destroy original select2, so the clone does not include
// extra stuff select2 generates.
$('#select0').select2('destroy');
// Now create our clone
let clone = $("#row_examenes .cloned").clone()
clone.find('input[name="username"]').attr("id", "name" + clones);
clone.find('input[name="email"]').attr("id", "email" + clones);
clone.find('input[name="phone"]').attr("id", "phone" + clones);
clone.find("select").attr("id", "select" + clones);
// HTML is updated, add it to the DOM
clone.appendTo($("#clone"));
// Reinitialise the original select2
$('#select0').select2();
// And initialise our new select2
$('#select' + clones).select2();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<button>Create a clone</button>
<div id="row_examenes">
<div class="cloned">
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="name0" name="username" placeholder="Enter Full Name" type="text" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="email0" name="email" placeholder="Enter VALID EMAIL and check the result" type="email" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="phone0" name="phone" placeholder="Enter Phone e.g.: +363012345" type="text" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<select class="chosen-select" multiple="multiple" id="select0" >
<div clas="options">
<option value="1">Google</option>
<option value="1">Amazon</option>
<option value="1">Facebook</option>
<option value="1">Airbnb</option>
</div>
</select>
</div>
</div>
</div>
</div>
<div class="row box" id="clone"></div>

How to load the value of a drop down to a text box when selected

I am working on a front end project and have a set of Dropdown list where it can be selected.
My requirement is when I select a specific dropdown name the corresponding value of it has to load in the next text box.
This is the code that I tried.
$('#selseriessetupid').change(function(){
var employeenumber = $(':selected',this).data('lastused');
$('.form-control').val(employeenumber);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-3 col-lg-3 col-xs-3 col-sm-3 uiblock">
<div class="form-group uicontrol editControl" data-displaytype="dropdownlist" data-fieldname="seriessetupid" data-templateitemid="8875">
<label class="clsCaption">Employee Number</label>
<select class="form-control" name="seriessetupid" id="selseriessetupid">
<option value="0">Please select Status</option>
<option data-lastused="01" value="126">FIN1</option>
<option data-lastused="01" value="124">FIN</option>
<option data-lastused="01" value="125">CRM</option></select></div>
</div>
<div class="col-md-3 col-lg-3 col-xs-3 col-sm-3 uiblock">
<div class="form-group uicontrol editControl" data-displaytype="textbox" data-fieldname="employeenumber" data-templateitemid="8796">
<label class="clsCaption">Employee ID</label>
<input type="text" placeholder="Employee ID" class="form-control " name="employeenumber" id="employeenumber">
</div>
</div>
</div>
You can get the value of Select dropdown (#selseriessetupid) using .val() function of jquery and try setting it in the #employeenumber value.
$(document).ready(function() {$('#selseriessetupid').change(function(){
$('#employeenumber').val($('#selseriessetupid').val());
});
});
You have to use the next() method of Jquery. Try this one
$('#selseriessetupid').change(function(){
var employeenumber = $(':selected',this).data('lastused');
$(this).next('.form-control').val(employeenumber);
});
Note It will not work in all situations cause your are using an ID selector. change it to class to work properly.

how to get multiple option from select without pressing control key?

I have 2 'select' in my html code and from first select, i want to choose only one option and from second select i want to choose multiple options. I have written code in jquery to get multiple options from select.
JQuery
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
and this code is working perfect, but the problem is my second select is working fine but in my first select i am not able to choose any option and i just want to get only one option from first select.
HTML
<div class="form-group">
<div class="col-sm-3">
<label style="width: 100%;" class="control-label"
th:text="#{CLONE.MASTERID}"></label>
</div>
<div class="col-sm-9">
<select class="form-control" id="cloneMasterIds">
<option value="">Select Master Device Id</option>
<option th:each="master : ${masterIds}" th:value="${master.value}"
th:utext="${master.value}">Wireframe</option>
</select>
<p class="field-error hidden-true"
id="SerialNumber-Error" th:text="#{ERROR.CLONE.MASTERID}"></p>
</div>
</div>
<!-- Child IDs -->
<div class="form-group">
<div class="col-sm-3">
<label style="width: 100%;" class="control-label"
th:text="#{CLONE.CHILDID}"></label>
</div>
<div class="col-sm-9">
<select class="form-control select-checkbox" id="cloneChildIds"
multiple="multiple">
<option th:each="child : ${childIds}" th:value="${child.value}"
th:utext="${child.value}">Wireframe</option>
</select>
<p class="field-error hidden-true"
id="SerialNumber-Error" th:text="#{ERROR.CLONE.CHILDID}"></p>
</div>
</div>
Select the second select statement by id. Handle the mousedown and mousemove events:
$("#cloneChildIds").mousedown(function(e){
e.preventDefault();
var select = this;
var scroll = select.scrollTop;
e.target.selected = !e.target.selected;
setTimeout(() => select.scrollTop = scroll, 0);
$(select).focus();
}).mousemove(e => e.preventDefault());

setting only the input field as empty string without the selection tag

I have a container that consists of a couple of inputs tag and one select tag. All of them have className, let's call it "contact". In jquery , I am accessing all of them through "contact". Also, there is checkbox that disables when you check it and when toy uncheck it, it empties the input fields and remove disable . The thing i want to do I want when i uncheck the checkbox, I want to set the the input fields as empty string, which i did, but what i did include the selection tag which i do not set as empty string
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").val("");
}
});
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10 contact">
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
There is error but i dont know what is it
Include the $ reference in your code. That means add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
in your html
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").each(function(i, el){
if($(el)[0].nodeName != "SELECT"){
$(el).val("");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10 contact">
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
</div>
Sorry, I don't have enough reputation to comment.
I tested your code and that works well as you want.
You missed selecting jquery in stackoverflow code snippet.
please check follow code.
If it's not working even after you added jquery script, then please let me know jquery version you used. (don't forget to add jquery cdn or picking jquery library in code snippet editor)
if you want to keep selection of select element please remove the contact class in there like below.
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10"> <!-- I removed contact class in here to keep selection -->
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>

JQuery: show() and hide() targeting more than one div doesn't work?

What I am trying to achive here is to target a couple of divs to show or hide depanding on what the val is. In this case it doesn't work, when I have only one div target it works, but only for 1 of the to hide not two of them. I am not really sure if I can target multiple divs ?
$(document).ready(function (){
$("#state").change(function() {
// foo is the id of the other select box
if ($(this).val() == "twoChoices") {
$("#foo", "#foo1", "#foo2", "#foo3").show();
}else{
$("#foo", "#foo1", "#foo2", "#foo3").hide();
}
});
<div class="form-group">
<label for="Choice" class="col-sm-8 control-label">How many?</label>
<div class="col-sm-2">
<select id="state" class="form-control">
<option value="oneChoice">1</option>
<option value="twoChoices">2</option>
</select>
</div>
</div>
<div id="foo" class="form-group">
<label for="Choice" class="col-sm-8 control-label">First to be</label>
<div class="col-sm-3">
<select id="mixOrSingle" class="form-control">
<option value="mix">Mix</option>
<option value="single">Single</option>
</select>
</div>
</div>
<div id="foo2" class="form-group">
<label for="Choice" class="col-sm-8 control-label">Second to be</label>
<div class="col-sm-3">
<select id="mixOrSingle" class="form-control">
<option value="mix">Mix</option>
<option value="single">Single</option>
</select>
</div>
</div>
Its because, the way you have used the multiple-selector is wrong.
Try,
$("#foo,#foo1,#foo2,#foo3").show();
Full code,
$(document).ready(function (){
$("#state").change(function() {
$("#foo,#foo1,#foo2,#foo3").toggle($(this).val() == "twoChoices");
});
});
You might be better using classes too, to keep this cleaner and easier to maintain ?
Say html:
<div id="foo" class="form-group twoChoice"></div>
<div id="foo1" class="form-group twoChoice"></div>
<div id="foo2" class="form-group twoChoice"></div>
and JS
$("#state").change(function() {
$("."+$(this).val()).toggle();
/* or what ever logic */
});
Your current example makes no sense, as, whatever the value, it hides the same elements, but I guess that's just to show the problem. The key would be to target the class rather than all those chained id's.
Update, forgot to say. A nice convention too is to name those classes more verbose, so easier to see what is happening in 12 months time :)
eg
<div id="foo" class="form-group js-hiddenBy_twoChoice"></div>
<div id="foo1" class="form-group js-hiddenBy_twoChoice"></div>
<div id="foo2" class="form-group js-hiddenBy_twoChoice"></div>
JS
$("#state").change(function() {
$(".js-hiddenBy_"+$(this).val()).hide();
});

Categories

Resources