How to Hide/Show 'div' using jQuery? - javascript

How can I show the text box depending on the user's selection in a dropdown box?
<select name="sites" id="select5" required="yes">
<?php
for($i=0;$i<=128;$i++){
echo "<option>".$i."</option>";
}
?>
</select>
<div id="YES">
Other: <input class="input-text" type="text" name="name"/>
</div>
If the user selects 1 - the text box will not show.
Then if the user selects more than 2 -> the <div id="YES"> will show.
Here's my jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#YES').hide();
$("#select5").change(function(){
$('#YES').hide('slow');
$("#" + this.value).show('slow');
});
});
</script>
Any suggestions?

You can call the hide/show based on the value of the select like
$(document).ready(function () {
$('#YES').hide();
$("#select5").change(function () {
$('#YES')[this.value > 1 ? 'show' : 'hide']('slow');
});
});
Demo: Fiddle

try this out
$('#select5').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if(valueSelected == 1){
$('#YES').show();
}
else{ $('#YES').hide();}
});

Related

jQuery change values based on attributes

I have an input class and I want to change it to select form attribute.
So far I have something similar that is working on my h2.title that change the word from Apple to Orange.
Example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
if (){
$(document).ready(function(){
$(document).live({
mouseover: function(e) {
$('h2.title').each(function() {
var text = $(this).text();
text = text.replace('Apple', 'Orange');
$(this).text(text);
});
}
});
});
}
</script>
And I really like this to be converted to select form attribute
<input class = "form-input ng-pristine ng-untouched ng-valid ng-empty ng valid-maxlength" id="Banana" maxlength = "2000" name="Banana" type=text"
Is there a way to work about this? with 2 select options
Yes, you can do this:
text = text.replace('Apple', $(this).attr("name"));
Here is a demo:
$(document).ready(function() {
$(document).on("mouseover", function(e) {
$('h2.title').each(function() {
var text = $(this).text();
text = text.replace('Apple', $(this).attr("name"));
$(this).text(text);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="title" name="Banana">Apple</h2>
<h2 class="title" name="Orange">Apple</h2>
<h2 class="title" name="Pineapple">Apple</h2>
<h2 class="title" name="Grape">Apple</h2>

Checkbox select deselect all and perform function

I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle
CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>

change the Input Name based on the multiple dropdown selection in html form?

I am trying to create add/remove form fields dynamically with jQuery where the user can submit multiple queries based on the dropdown selections. At the end, it should generate URL with a combination of selection.So far I have managed to create add/remove form fields with the option of multiple queries.
For example, if the user submits input for a car then it will generate URL like:
exmaple.com/?car=xxx
and which is working.
If a user submits input for car and bike then it should generate:
exmaple.com/?car=xxx&bike=yyy
but it is generating like:
exmaple.com/?car=xxx&car=yyy
So how can I solve this issue? Thank you in advance.
$(function() {
$.fn.addmore = function(options) {
var moreElement = this,
singlePreSelectedValue = '',
selectedValue = [],
defaultOption = {
addText: 'add more',
removeText: 'Remote',
selectBoxDuplicate: true,
avoidDuplicationSelection: function(e) {
var o = e;
if ($.inArray($(o).val(), selectedValue) != -1) {
$(o).val(singlePreSelectedValue);
alert('Value already selected.');
} else {
var hasSelectValue = true;
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() == 'select') {
hasSelectValue = false;
return false;
}
});
}
},
prevSelectedValue: function(e) {
var o = e;
selectedValue = [];
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
selectedValue.push($(this).val());
}
});
singlePreSelectedValue = $(o).val();
}
}
defaultOption = $.extend(true, defaultOption, options);
/* $(this).find('select').prepend('<option value="select" selected>Select</option>');*/
$(moreElement).after('' + defaultOption.addText + '');
$('[data-id="more"]').click(function() {
var dataMore = this,
removeDuplication = [];
$(dataMore).before($(moreElement).clone().find('input').not('input[type="submit"]').val('').end().end().find('select.removeDuplication').focus(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.prevSelectedValue(this);
}
}).change(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.avoidDuplicationSelection(this);
}
}).end().append(function() {
return $('<i class="fa fa-trash"></i> ' + +'').click(function() {
$(this).parent().remove();
});
}));
if (!defaultOption.selectBoxDuplicate) {
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
removeDuplication.push($(this).val());
}
});
$.each(removeDuplication, function(i, v) {
$('.removeDuplication').last().find('option[value="' + removeDuplication[i] + '"]').remove();
});
}
});
$('.removeDuplication').focus(function(e) {
defaultOption.prevSelectedValue(this);
}).change(function() {
defaultOption.avoidDuplicationSelection(this);
});
return this;
}
$('dl').addmore({
addText: 'Add',
removeText: 'Remove',
selectBoxDuplicate: false
});
});
$(document).ready(function() {
$("select").change(function() {
var str = $(this).val();
$("#searchtermid").attr("name", str);
});
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="navbar-form" action="" method="get" action="demo_form.asp">
<dl>
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</dl>
<input class="btn btn-primary" type="submit" value="Submit">
</form>
After getting input from Standard Quality, I have modified my scripts and html.
https://jsfiddle.net/paul85/wjhqszmg/
But still is not letting the user submit input form. Most important, when user will submit from it should redirect to a page for correctly generated URL.
If user submit input for car and bike then redirecting page address or URL will be:
exmaple.com/?car=xxx&bike=yyy
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="/results.html" method="get">
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication">
<option value="car" >Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>
</div>
</div>
<button class="add_field_button">Add More Fields</button>
<input class ="btn btn-primary" type="submit" value="Submit" >
</form>
JAVASCRIPT
$(document).ready(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication">\
<option value=""></option>\
<option value="car">Car</option>\
<option value="bike">Bike</option>\
<option value="plane">Plane</option>\
</select>\
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).val()+' already selected.');
}
});
});
/*$(form).submit(function(e){*/
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
if (query.type !=""){
queries.push(query);
} else{
slectedall=false;
}
});
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
if (query.value.trim() ===""){
fillupfield=false;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Please insert your searchterm.');
} else {
$("form").submit();
}
}
});
});
It looks like you're extending jQuery, which isn't necessary for this, and is contributing to making the code much less legible. To be honest, I haven't even dug through it to find the problem -- instead, I wrote something from scratch. StackOverflow snippets don't allow forms, so here's a working JSBin: http://jsbin.com/gokodaluna/edit?html,js,output
(Note that I've changed your HTML markup a little bit)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="" method="get" action="demo_form.asp">
<div class="fields">
<div class="form-field">
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<h2 id="final-url"></h2>
</body>
</html>
Javascript:
/* Save your initial variables */
var form = $('#main-form');
var formFields = form.find('.fields')
var addButton = $('#form-add');
var emptyInput = $('.form-field').clone(); // clone this at initialization so we always have an empty field
var finalUrl = $("#final-url");
addButton.on('click', function() {
emptyInput.clone().appendTo(formFields);
/* clone this again so our initial field is always empty and available */
})
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
queries.push(query);
});
var url = window.location.href;
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
url += ampOrQ + query.type + "=" + query.value;
}
/* print the URL into the dom if you want to see it working */
finalUrl.text(url);
/* or forward users to the new URL you've generated */
window.location.href = url;
})
Edit: in the revised code in your question, you're calling $("form").submit() in that if-else statement. When you trigger this, the larger function is still catching the submit event, so it's immediately running e.preventDefault() again. If you need to simply forward the user to the new URL, just set it with window.location.href =. See the last few lines of my (edited) code above.

Enable a text box only when 1 of the radio button is clicked

I have 2 radio button ie yes and no. When I select yes the text box as to get enabled. When i click no the text box as to be disabled. How to enable the text box when I click on Yes. Here is the code. Please tel me how to enable and disable it using javascript.
<script type="text/javascript">
$(function() {
$("#XISubmit").click(function(){
var XIyop= document.forms["XIForm"]["XIyop"].value;
var XIForm = $('form[name=XIForm]');
var XIAlmnus = XIForm.find('input[name=XIAlmnus]:checked').val();
if (XIAlmnus == null || XIAlmnus == "")
{
alert("Please select Parent is an Alumnus (old Boy) of this school");
return false;
}
document.getElementById("XIForm").submit();
});
</script>
<!-- html code-->
<html>
...
<label>Parent is an Alumnus (old Boy) of this school </label> &nbsp&nbsp
<input type='radio' name='XIAlmnus' value='Yes' id="XIyes"/>Yes
<input type='radio' name='XIAlmnus' value='No' id="XIno"/>No</td>
<label>If Yes, Year of passing </label> &nbsp&nbsp
<input type="textbox" name="XIyop" id="XIyop" >
...
</html>
I think, you should use some general handler for this: http://jsfiddle.net/maximgladkov/MvLXL/
$(function() {
window.invalidate_input = function() {
if ($('input[name=XIAlmnus]:checked').val() == "Yes")
$('#XIyop').removeAttr('disabled');
else
$('#XIyop').attr('disabled', 'disabled');
};
$("input[name=XIAlmnus]").change(invalidate_input);
invalidate_input();
});
first make the text box disabled.
<input type="textbox" name="XIyop" id="XIyop" disabled>
When radio button clicked, check and enable it.
if(document.getElementById('XIyes').checked) {
document.getElementById("XIyop").disabled = false;
}else if(document.getElementById('XIno').checked) {
document.getElementById("XIyop").disabled = true;
}
$(function() {
$('input[name="XIAlmnus"]').on('change', function() {
if ($(this).val() == 'Yes') {
$("#XIyop").prop('disabled', false);
} else {
$("#XIyop").prop('disabled', true);
}
});
});
<input type="textbox" name="XIyop" id="XIyop" disabled>
if(document.getElementById('XIyes').attr('checked')) {
document.getElementById("XIyop").disabled = 'true';
}
if(document.getElementById('XIno').attr('checked')) {
document.getElementById("XIyop").disabled = 'false';
}
HTML:
<label>Parent is an Alumnus (old Boy) of this school </label> &nbsp&nbsp
<input type='radio' name='XIAlmnus' value='Yes' id="XIyes"/>Yes
<input type='radio' name='XIAlmnus' value='No' id="XIno"/>No
<br/>
<label>If Yes, Year of passing </label> &nbsp&nbsp
<input type="textbox" name="XIyop" id="XIyop" disabled>
JS:
document.getElementById('XIyes').onchange = displayTextBox;
document.getElementById('XIno').onchange = displayTextBox;
var textBox = document.getElementById('XIyop');
function displayTextBox(evt){
if(evt.target.value=="Yes"){
textBox.disabled = false;
}else{
textBox.disabled = true;
}
}
Please see working demo here. Thank you I hope this will help you.

When I will click on a href link it will check all checkbox after related this link

I have a links named All and none. When I click on All, I want it to check all checkboxes related with it and change it's link text to none.
When I click again I want it to uncheck all of the checkboxes.
I have some code which I can use to check all boxes with a checkbox. But now I want to check all boxes with a link. Please see, here is this demo code (also on jsfiddle):
<script type="text/javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
$(document).ready(function () {
$("input[type=checkbox]").click(updateCount);
updateCount();
function updateCount () {
var count = $("input[type=checkbox].case:checked").length;
$("#count").text(count);
$("#status").toggle(count > 0);
};
});
</script>enter code here
</head>
<body>
<H2>why counting wrong in crome, Ie </H2>
select all
<input type="checkbox" id="selectall"/>
<input type="checkbox" class="case" name="case" value="1"/>
<input type="checkbox" class="case" name="case" value="2"/>
<input type="checkbox" class="case" name="case" value="3"/>
<input type="checkbox" class="case" name="case" value="4"/>
<input type="checkbox" class="case" name="case" value="5"/>
<div id="status">
<p id="count">0</p>
</div>
</body>
http://jsfiddle.net/kdEmH/24/
Try to get it this way, i just guessed a link <a> with an id of #allNone and put the .prop() function to check and uncheck the checkboxes:
$('#allNone').on('click', function (e) {
e.preventDefault();
(this.text == 'Check All') ?
$(this).text('Check None').nextAll('.case').prop('checked', true) :
$(this).text('Check All').nextAll('.case').prop('checked', false);
});
Demo
In your HTML part, add a link like :
Click me to toggle all checkboxes
In your Javascript part, add :
$("a#select_all_link").click(function(){
if($('.case:checked').length > 0)
$('.case').attr('checked', false);
else
$('.case').attr('checked', true);
});
Please see working example here
Edit : Names now changed wrt checkboxes state (checked or not)
Try this: Demo :
Add a <A> tag to html code:
<a id="selectall" href="#">select all</a>
Add this function to java-script code:
$(function(){
var state=true;
$("#selectall").click(function () {
$('.case').attr('checked', state);
state=!state;
var obj = document.getElementById("selectall");
if(state)
{
obj.innerText="select all";
}
else
{
obj.innerText="clear all";
}
});
Complete Code
$(function(){
var state=true;
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', state);
state=!state;
var obj = document.getElementById("selectall");
if(state)
{
obj.innerText="select all";
}
else
{
obj.innerText="clear all";
}
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
$(document).ready(function () {
$("input[type=checkbox]").click(updateCount);
updateCount();
function updateCount () {
var count = $("input[type=checkbox].case:checked").length;
$("#count").text(count);
$("#status").toggle(count > 0);
};
});
Might not be what you're looking for, but it's a quick way of doing the toggle thing:
$('a').click(function() {
var $cbs = $('.case');
$cbs.prop('checked', !$cbs.prop('checked'));
return false;
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
All
<input type="checkbox" class="case" value="1"/>
<input type="checkbox" class="case" value="2"/>
<input type="checkbox" class="case" value="3"/>
<input type="checkbox" class="case" value="4"/>
<input type="checkbox" class="case" value="5"/>
<div id="status">
<p id="count">0</p>
</div>
</body>
<script type="text/javascript">
$("document").ready(function() {
$("#link").click(function(){
$a = $(this);
var action = $a.data('action');
if(action == "all"){
$('.case').attr("checked","true");
$a.text("None").data("action","none");
}
if(action == "none"){
$('.case').removeAttr("checked");
$a.text("All").data("action","all");
}
updatecount();
return false;
})
$(".case").click(function(){
if($(".case").length == $(".case:checked").length){
$("#link").text("None").data("action","none");
}else{
$("#link").text("All").data("action","all");
}
updatecount();
})
})
var updatecount = function(){
$("#count").text($(".case:checked").length);
}
</script>
</html>

Categories

Resources