Change selectbox to textfield and vice versa - javascript

I have a table in which there are three columns (A: datefield, B: selectbox, C: checkbox).
Now when someone checks on the checkbox, the column(B) having selectbox should convert to a column textfield. That means I want to convert selectbox to textfield and vice versa on change of the checkbox event. Is that possible?? If so how? (using js, no jquery please)
Reply is greatly appreciated.

Try as below,
<html>
<body>
<script type="text/javascript">
function toggleSelect() {
var isChecked = document.getElementById("check").checked;
if(isChecked) {
document.getElementById("toggle").innerHTML = "<input type='text' id='txt'></input>";
} else {
document.getElementById("toggle").innerHTML = "<select> <option value='1'>1</option> </select> ";
}
//alert(isChecked);
}
</script>
<table>
<tr>
<td> DateField </td>
<td id="toggle">
<select> <option value="1">1</option> </select>
</td>
<td> <input type="checkbox" id="check" onchange="javascript:toggleSelect();">change</input></td>
</tr>
</table>
</body>
</html>

Place two div tags where
one contains the component which you want to change (for this div give a class name "comp1 visible" and in the CSS set the style has display: block )
and another one div with the component you would want to replace ( for this div give a class name "comp2 hidden" and in the CSS set the style has display:none )
use the onclick event to call the function ...
function insertitem(rvalue){
if(rvalue.value==1){
var temp=document.getElementsByClassName("comp1");
temp[0].classList.remove("hidden");
temp[0].classList.add("visible");
}
else if(rvalue.value==2){
var temp=document.getElementsByClassName("comp2");
temp[0].classList.remove("hidden");
temp[0].classList.add("visible");
}
}
this should work.. PS: since you dint post any of ur code .. i couldnt explain much

Related

Apply text from selected dropdownmenu item to input field (html,javascript)

When i select an item from a dropdownmenu id like to view it in a input field, if another item is selected i want to add this to the input field separated by a comma.
Currently this is the html:
<div>
<input type="text" id="box" placeholder="Using..." style="width: 400px">
<select style="width: 180px" id="drop">
<option value="" disabled selected>Select</option>
{% for stuff in stuffs%}
<option value="{{stuff}}" onclick="ApplyField(drop,box)">{{stuff}}</option>
{% endfor %}
</select>
</div>
and the javascript:
<script>
function ApplyField(drop_id,box_id)
{
var e = document.getElementById(field_id);
var selectedItem = e.options[e.selectedIndex].text;
if (document.getElementById(box_id).text == "")
document.getElementById(box_id).text = selectedItem;
else
document.getElementById(box_id).text = document.getElementById(box_id).text + "," + selectedItem;
}
</script>
But somehow my script wont set the input box item to the selecteditem altough the code seems logical to me. This is my first time writing javascript so its likely that i missed something trivial. Any help is appretiated.
I believe that your drop_id and box_id are not the correct way to select the element in JavaScript. Also not quite sure what is going on with the {{stuff}} template to be honest
Can you use jQuery? If so, have a look at http://www.w3schools.com/jquery/html_val.asp

Elements not staying visible when function is called

I am creating an input to capture data related to fish that are caught. When the submit button is clicked I see a tr quickly show up then disappear, likewise, I see the console.log message show up for a split second then disappear.
Code is posted below, however running the code snippet doesn't look like it does when seen through a browser. I set up a live site for this here: http://fishrecord.jwhdesign.net/
I realize this is probably simple for most of you to figure out, so no need to tell me how dumb I am as I already know that.
Any help is very much appreciated.
function displayFishData() {
var table = document.getElementById("test"); //find "test" AKA the table
var row = table.insertRow(); //add row to that table
row.insertCell(); //insert cell to table
console.log("adding a row to the table");
}
table {
border: 1px solid black;
margin: 0 auto;
width: 80%;
}
<h1>Fish Record</h1>
<form>
Species:
<select>
<option value="blank"></option>
<option value="Northern Pike">Northern Pike</option>
<option value="Largemouth Bass">Largemouth Bass</option>
<option value="Smallmouth Bass">Smallmouth Bass</option>
<option value="Chain Pickerel">Chain Pickerel</option>
<option value="Pike-Pickerel Hybrid">Pike-Pickerel Hybrid</option>
<option value="Panfish">Panfish</option>
<option value="Other">Other</option>
</select>
Weight (lbs):
<input type='number'></input>
Length (inches):
<input type='number'></input>
Comments:
<input rows="1"></input>
<br>
<button onclick="displayFishData()">Submit</button>
</form>
<table id="test">
<thead>
<tr>
<th>Species</th>
<th>Weight (lbs)</th>
<th>Length (inches)</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This is because your button is currently refreshing the page,
If you add
type="button"
to the button it will display an extra tr and show the message in the console
The default value for the type attribute of button element is submit. And thus on click of the button it is submiting the form
Replace
<button onclick="displayFishData()">Submit</button>
to
<button type="button" onclick="displayFishData()">Submit</button>
First of all add the displayFishData() to the form not the button! it would look like this <form onsubmit="displayFishData()"> this would help you to control the form output in a better way.
BTW using <input type="submit" /> is a better practice than <button></button>
And for a simpler data inserting do the following:
var table = document.getElementById("test");
var row = table.insertRow();
var e1 = row.insertCell(0);
var e2 = row.insertCell(1);
// keep adding as much rows as you got
// this change the innerHTML
e1.innerHTML = "the data you got from a form element";
// repeat that

creating table header with javascript

I am having two issues with my table, One of them is that I want it to only show when I click a button but when i do it shows and then hides and the other is how do I send a parameter based on the select option to this createtable function
This is part of my code
<form class="form-inline" role="form">
<select multiple class="form-control" style = "width:250px"id = "theselect">
<option selected disabled> Chose a number </option>
<option> all </option>
<option> 1 </option>
<option> 2 </option>
</select>
<button type="submit" id = "load" class="btn btn-default">Load</button>
</form>
<div id ="test">
</div>
<script type = "text/javascript">
$(document).ready(function(){
$("#example").hide();
$("#load").click(function(e){
$("#example").show();
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border>";
....
....
$('#test').append(contents); append it to div
}
$(document).ready(createTable(1));
</script>
Thank you
The reason that the table is getting hidden again is because you've set type="submit" on your button. This means that after the click event handler is done processing, it will submit the form, which causes the page to reload. When it reloads, the table is hidden again. If you change it to type="button" that will prevent that.
You can get the currently selected value of the select, using jquery, with this:
$('#theselect').val();
You can then pass this in to your createTable function (or just get the value using that code, from within the function itself).
Also, it's a really bad idea to create markup from within your JavaScript. It's going to make future maintenance a nightmare, and if it gets complex enough, it could start causing performance issues. It's much better to keep your markup separate, and then show/hide it as needed via JS.
Take a look at this example. It gets the selected values, and inserts them into a table, and table into the dom... HTH.
$(document).ready(function(){
$("#load").click(function(e){
var bits = $('#theselect').val();
$("#example").hide();
$('#test').html('');
createTable(bits)
$("#example").show();
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border><tbody><tr><td>"+param+"</td></tr></tbody></table>";
$('#test').append(contents)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select multiple class="form-control" style = "width:250px"id = "theselect">
<option selected disabled> Chose a number </option>
<option> all </option>
<option> 1 </option>
<option> 2 </option>
</select>
<button id = "load" class="btn btn-default">Load</button>
<div id ="test"></div>
Try this:
$(document).ready(function(){
$("#load").click(function(e){
createTable($("#theselect").val());
$("#example").show(); // In case of class 'display' gives it 'display:none'
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border>";
$('#test').append(contents);
}
#example doesn't exists at the beginning so I removed $("#example").hide().

function find() with variable as a parameter returns empty object

I'm refactoring a code on a generated web page and there is a div (tab) which can occur multiple times. There is a small section with check-boxes on each and every such div, which lets you choose other divs that will be shown.
Since there is a chance for other divs to be added to the page I wanted to make the code modular. Meaning that every checkbox id is identical to the class of the div, which it should toggle, with added "Div" at the end. So I use checked id, concat it with "." and "Div" and try to find it in closest fieldset.
Here is the almost working fiddle: http://jsfiddle.net/ebwokLpf/5/ (I can't find the way to make the onchange work)
Here is the code:
$(document).ready(function(){
$(".inChecks").each(function(){
changeDivState($(this));
});
});
function changeDivState(element){
var divClassSel = "." + element.attr("id") + "Div";
var cloField = element.closest("fieldset");
if(element.prop("checked")){
cloField.find(divClassSel).toggle(true);
} else {
cloField.find(divClassSel).toggle(false);
}
}
Aside for that not-working onchange, this functionality does what it's intended to do. However only on the jsfiddle. The same code does not work on my page.
When I used log on variables from the code, the result was as this
console.log(divClassSel) => inRedDiv
console.log($(divClassSel)) => Object[div.etc.]
console.log(cloField) => Object[fieldset.etc.]
//but
console.log(cloField.find(divClassSel)) => Object[]
According to firebug the version of the jQuery is 1.7.1
Since I can't find any solution to this is there any other way how to make it in modular manner? Or is there some mistake I'm not aware of? I'm trying to avoid writing a function with x checks for element id, or unique functions for every check-box (the way it was done before).
Remove the inline onchange and also you don't need to iterate on the elements.
Just write one event on class "inCheckes" and pass the current element reference to your function:
HTML:
<fieldset id="field1">
<legend>Fieldset 1</legend>
<table class="gridtable">
<tr>
<td>
<input id="inRed" class="inChecks" type="checkbox" checked="checked" />
</td>
<td>Red</td>
</tr>
<tr>
<td>
<input id="inBlue" class="inChecks" type="checkbox" />
</td>
<td>Blue</td>
</tr>
</table>
<div class="inDivs">
<div class="inRedDiv redDiv"></div>
<div class="inBlueDiv blueDiv" /></div>
</fieldset>
<fieldset id="field2">
<legend>Fieldset 2</legend>
<table class="gridtable">
<tr>
<td>
<input id="inRed" class="inChecks" type="checkbox" />
</td>
<td>Red</td>
</tr>
<tr>
<td>
<input id="inBlue" class="inChecks" type="checkbox" checked="checked" />
</td>
<td>Blue</td>
</tr>
</table>
<div class="inDivs">
<div class="inRedDiv redDiv"></div>
<div class="inBlueDiv blueDiv" /></div>
</fieldset>
JQUERY:
$(document).ready(function () {
$(".inChecks").change(function () {
changeDivState($(this));
})
});
FIDDLE:
http://jsfiddle.net/ebwokLpf/4/
As gillesc said in the comments changing the javascript code to something like this made it work.
$(document).ready(function(){
$(".inChecks").each(function(){
changeDivState($(this));
});
$(".inChecks").on("change", function() {
changeDivState($(this));
});
});
function changeDivState(element){
var divClassSel = "." + element.attr("id") + "Div";
var cloField = element.closest("fieldset");
if(element.prop("checked")){
cloField.find(divClassSel).toggle(true);
} else {
cloField.find(divClassSel).toggle(false);
}
}
You asked for an other way how to make it in modular manner:
You can create a jQuery plugin which handles the logic for one fieldset including changing the color when clicking different checkboxes.
This way all logic is bundled in one place (in the plugin) and you can refine it later on.
For example you can decide later on that the plugin should create the whole html structure of the fieldset (like jQuery UI slider plugin creates the whole structure for the slider element) and therefore change the plugin.
The code for the (first version) of your jQuery plugin could look something like this:
$.fn.colorField = function() {
var $colorDiv = this.find('.colorDiv'),
$inputs = this.find('input'),
$checked = $inputs.filter(':checked');
if($checked.length) {
// set initial color
$colorDiv.css('background', $checked.attr('data-color'));
}
$inputs.change(function() {
var $this = $(this),
background = '#999'; // the default color
if($this.prop('checked')) {
// uncheck the other checkboxes
$inputs.not(this).prop('checked', false);
// read the color for this checkbox
background = $(this).attr('data-color');
}
// change the color of the colorDiv container
$colorDiv.css('background', background);
});
};
The plugin uses the data-color-attributes of the checkboxes to change the color of the colorDiv container. So every checkbox needs an data-color attribute, but multiple divs for different colors are not necessary anymore.
The HTML code (for one fieldset):
<fieldset id="field1">
<legend>Fieldset 1</legend>
<table class="gridtable">
<tr><td><input id="inRed" class="inChecks" type="checkbox" checked="checked" data-color='#ff1005' /></td><td>Red</td></tr>
<tr><td><input id="inBlue" class="inChecks" type="checkbox" data-color='#00adff' /></td><td>Blue</td></tr>
</table>
<div class="colorDiv"></div>
</fieldset>
Now you can create instances with your colorField-plugin like this:
$(document).ready(function(){
$('#field1').colorField();
$('#field2').colorField();
});
Here is a working jsFiddle-demo

Displaying a textbox depending on selection from the select box

I have an application in which the user needs to enter Industry while filling out a form. We have several pre-made choices in the drop down box, but he also needs to enter manually. He can click on Other, and a input box should be displayed asking for the manual entry.
I have written this javascript codes which solves my purpose, but when the page loads..I can see the box there even when the user hasn't selected anything.
How can I fix this, so this only shows a checkbox when the user clicks Other, or removes the checkbox if the user clicks on another option after hitting Other once.
HTML code :p
<tr>
<td>Industry*</td>
<td>
<select name="industry" id="industry" class="validate[required]" onchange="javascript: test()">
<option value="BPO">BPO</option>
<option value="Call Centre"> Call Centre </option>
<option value="Software">Software</option>
<option value="Networking">Networking</option>
<option value="Management">Management</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="text" name="industryo" id="industryo" placeholder="Enter Manually">
</td>
</tr>
JS
<script>
function test()
{
//alert("something");
var industry = document.getElementById('industry').value;
if(industry == "Other")
{
$( document ).ready(function() {
// Handler for .ready() called.
$('#industryo').show();
});
}
else
{
$( document ).ready(function() {
$('#industryo').hide();
});
}
}
</script>
Any suggestion is helpful.
You can initially hide with CSS in your HTML:
<input type="text"
name="industryo"
id="industryo"
placeholder="Enter Manually"
style="display: none;" />
or in our CSS file:
#industryo { display: none; }
or with jQuery:
<script>
// Shorthand for $( document ).ready()
$(function() { $("#industryo").hide(); });
</script>
I think this is what you want. Initially hide your input, then show/hide it depending if the dropdown has "Other" selected. You can use the on change event to check that.
Demo here
//Hide initially
$('#industryo').hide();
$('#industry').on('change', function() {
if($(this).val() == "Other") {
$('#industryo').show();
} else {
$('#industryo').hide();
}
});

Categories