Remove characters between select elements - javascript

Hello this seems like a simple question but i can't figure a clean way to do this :
The aim of my developement was simply to remove some hour forms represented in a hh:mm:ss format.
I had to hide the selec entries for hours, minutes and seconds but i still have those 2 unhidden ugly ":" chracters remaining at the end of my selects and i can't figure a proper way to remove them !
Here is the HTML part generated by my JSP :
<span class="dateTime">
<script type="text/javascript">.....</script>
<script src="test.js" type="text/javascript</script>
<select id="x">
<option value="">Hour></option>
</select>
:
<select id="x">
<option value="">Minute></option>
</select>
:
<select id="x">
<option value="">Second></option>
</select>
</span>
I can't modify this code as it generated in my jsp which is using standard classes. I would prefer to do this in javascript directly in my JSP like i did to hide the time fields.

You can do something like that :
var dateElement = document.getElementById('dateElem');
dateElement.childNodes.forEach(function(node){
// check if the node is a text node
if (node.nodeType === 3)
dateElement.removeChild(node);
})
I have to admit that it is not very nice but it works... :p You can be more precise on which node you delete as well ;)
PS: I assumed you can put an id on the element... if you cant, just get the element thanks to the className or try to find a way ;)

Related

Simple jquery/javascript dropdown menu with 2 outputs (1 img, 1 title)

Please forgive me I'm self-taught with large pockets of knowledge missing ><
I found some code (probably from you guys here at Stockoverflow!) and managed to get it to work in my site. There is only 1 change I need to make to my jquery but it's not working when I do it.
This is the unchanged version
(the dropdown list is what I am working on)
HTML
<div class="prints">
<div><img class="printShop" src="art_images/anime_art_prints/p000a.png" name="image-swap"></div>
<div><span class="titleName" name="title-swap">Title of Artwork</span></div>
<div>
<select name="printchoice" id="printchoice">
<option data-tname="Select" value="art_images/anime_art_prints/p000a.png">Please Select your Print</option>
<option data-tname="Selected One" value="art_images/anime_art_prints/p000b.png">A Sassy Catgirl</option>
<option data-tname="Selected Two" value="art_images/anime_art_prints/p000c.png">Mermaid Friends</option>
<option data-tname="Selected Three" value="art_images/anime_art_prints/p000d.png">Galaxy Girl</option>
</select>
</div>
</div>
JS
$(document).ready(function(){
$("#printchoice").change(function(){
$("img[name=image-swap]").attr("src",$(this).val());
});
$("#printchoice").change(function(){
$("span[name=title-swap]").html($(this).val());
});
});
This works how I want it, but it puts the text of the option's value="" into the title span. I want the options data-tname="" text to show instead. I tried to replace val() with data('tname') in the second paragraph to no avail. that just seems to break it :(
If it isn't too much of your time, could you take a quick look and see if it is something super simple that I need to change that can make it work how I need it to?
$("#printchoice").change(function(){
$("img[name=image-swap]").attr("src",$(this).val());
$("span[name=title-swap]").html($(this).find('option:selected').attr('data-tname'));
});

using a variable from drop down list

I'm attempting to create a dynamic drop down list, but after searching for hours I'm still completely stumped as to how to do it. So I am experimenting with variables in a list. This is the code I've started with.
<body>
<form method = "post">
<select id = "State" onchange = "a = this.options[selectedIndex].value;">
<option value = ""> Select a state</option>
<option value = "S3"> Pennsylvania</option>
<option value = "S4"> California</option>
<option value = "I4"> Texas</option>
<option value = "I5"> New York</option>
</select>
</form>
</body>
my question is what can I do with the variable 'a' so that I could create a dynamic drop down list based off it? One thing I had hoped to do was use an if-statement to display a second list. I wanted to remain on the same page too.
Note: I apologize if this seems like a basic question, but I've been scouring websites for answers and all I've figured out was that I can't send javascript variables to php, otherwise I'd have gotten this done forever ago
try this way
<select id="appamt" name="appamt">
<? while($amt=mysql_fetch_array($amount)){ ?>
<option value="<?=$amt['amount']?>"><?=$amt['amount']?></option>
<? } ?></select>
When your page detects the onchange event, what you need to do is either have all the combinations of options you want readily available but hidden on the page e.g. $('#sub-option1).hide(); and when the value is selected use $('#sub-option1).show();
Secondly you can have a ajax request that returns a JSON value of key=>value pairs, then use these key value pairs to dynamically build another dropdown using jquery .each() function.
Loop through your json values and add them to a previously hidden selector and then display it.
Hope this helps but if not email me and I will skype you through it.
Jim C

Dynamic Dropdown menu through php

I visited a website a few weeks ago and came across a dynamic drop down menu. I came across a functionality that I am now trying to replicate but do not know how. In the dropdown you picked the desired number of cars and then it reiterated input fields according to the number of cars chosen. I believe this was done through javascript and a loop was involved. Is there a term for this action or way to display things? Also an example of how to accomplish something similar would help?
This is done using java script ,
and here a hint
create a div and put inputs that you want inside it
<div id='controls'>
<input type="text" name="car_name" />
</div>
and using jQuery change event you can iterate view of controls div
i.e if you have a div with id container , where you will place new controls
$('select').change(function(){
var number = parseInt ($(this).val ());
//And do for loop here
for (var i=1;i<=number;i++){
$('#controls').clone().appendTo($('#container');
}
});
Please enhance this code to fit your requirement.
It's unlikely that this would be done with PHP, since that would require a page refresh.
It's more likely that it would be done with Javascript listening for the onChange event of the Select element (the drop down menu). When the event is detected, Javascript could show / hide div elements (one for each Car), or dynamically create / destroy them.
If you want it without refresh, you need use javascript, i have made one example here using jquery:
HTML CODE
<label>How many cars?</label>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="fields"></div>
JAVASCRIPT CODE
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="field_'+i+'"><label>Car '+i+'</label><br /><label>Model:</label> <input id="model_'+i+'" /><br /><label>Maker:</label> <input id="maker_'+i+'" /><br /><label>Year:</label> <input id="year_'+i+'" /><br /><div><br />';
}
$('#fields').html(content);
}
Here the example: http://jsfiddle.net/zbzjm/1/

Combobox; Show Different Description Text Upon Selection?

This is a sample code.
If we have 100 options e.g. and User selects an Option it shows the respective Description.
I made it work with Jscript but thats too long code to mess around. and is simple thing
Here is JS Version : http://jsfiddle.net/eHwVn/
and I want to Use Simple HTML
<select>
  <option value="i">ItemA</option>
  <option value="i">ItemB</option>
  <option value="i">ItemC</option>
  <option value="i">ItemD</option>
  <option value="i">ItemE</option>
  <option value="i">ItemF</option>
</select>
How to add description to each item using HTMl?
TO Get this:
(Sorry I cant post Images Yet)
http://i.stack.imgur.com/DSm4j.png
Thanks for Help
Peace!
Try the following JSFiddle : http://jsfiddle.net/3XTjH/
using the HTML :
<select id="example" onchange="showtext()">
<option value="http://www.cnet.com" data_info="Click here for Cnet, the primer technology site on the net!">Cnet</option>
<option value="http://www.cnn.com" data_info="Click here for CNN, one of the best sources online to get your news.">CNN</option>
<option value="http://www.geocities.com" data_info="Click here for Geocities, and receive 10 megs of free web space.">Geocities</option>
</select>
<br>
<textarea rows=5 cols=21 wrap="virtual" id="text"></textarea>
and the Javascript :
function showtext() {
var dropdown = document.getElementById("example");
var curOption = dropdown.options[dropdown.selectedIndex];
var info = curOption.getAttribute('data_info');
var txt = document.getElementById('text');
txt.value = info;
}
Every time you select a new option it find the currently selected option, and then find the value of the data_info attribute of that option and set the value of the text area to it.

How to fill <select> with text on <input type="text"> using Javascript?

I want to fill and submit a form like below:
<form action="http://www.test.com/school" method="post">
<select name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<input type="submit" value="submit" id="submitday">
I don't want to select from option so I have to create another form.
<form action="http://www.test.com/school" method="post">
<input type="text" name="days">
<input type="submit" value="submit" id="submitday">
When I want to choose Wednesday, I need to type the value 3 in a text box then click submit. It works.
But I want to know if any method that can make me just type Wednesday in text box and not the value and post it without any problem?
Your question isn't well defined enough and having an explicit goal always helps.
1.) Even though we're pretty much if not outright beyond the point where it's important to use id="same_as" name="same_as" having the same values I still highly recommend this practice (old Internet Explorer bug). You'll want to make good use of the label element (clicky clicky) as it gives users more area to click to give focus (element, checkbox, text, etc).
2.) You'll want to use the in operator to discover what tools you have available...
XHTML
<textarea id="dom_methods"></textarea>
JavaScript
for (i in document.getElementById('select_element_id')
{
document.getElementById('methods').value = document.getElementById('methods').value+'\n'+i;
}
This will let you discover different methods/functions/objects/etc that are associated with in example the select element. Keep in mind that each object may have it's own children. You can do...
for (i in window) {}
for (i in window.document) {}
for (i in document.getElementById('select_element_id')) {}
Good resources including Mozilla Developer Network here...
https://developer.mozilla.org/en/
My absolute biggest piece of advice is do not use frameworks as you will quickly veer off from learning the actual language and immediately inherit some high level issues you will not become aware of. People posting dollar signs ($) in JavaScript posts are usually good give-aways that they have not answered your question unless you have explicitly asked for a framework related answer.
If you revise your question and reply to my answer I'll be happy to append my answer to apply more directly to what you're trying to accomplish.
PART TWO
If you want to create an element you should use the createElement method...
Create the element and give it the value you want...
var d = document.getElementById('days');
var input_day = document.createElement('input');
input_day.setAttribute('id','days');
input_day.setAttribute('name','days');
input_day.setAttribute('type','text');
input_day.setAttribute('value',d.options[d.selectedIndex].text);
IMPORTANT! JavaScript has QUIET errors that you will battle for days before posting about them and someone casually pointing them out. So be exceptionally wary of using short names for variables (e.g. do not use var in = ''; as "in" is an operator and will cause a silent error) where your code simply won't execute or do odd stuff.
Now you have some VALID choices for putting this new element in to the page...
1.) Using appendChild will put the element at the end of the parent container...
document.getElementById('form_id').appendChild(d);
You should use fieldsets (usually one is fine) as a direct child to a form element...
<form action="" method="post">
<fieldset>
<!--everything form related goes here -->
</fieldset>
</form>
...in which case you could do the following (to help you get comfortable with examples and see them actually work before you)...
document.getElementById('form_id').getElementsByTagName('fieldset')[0].appendChild(d);
Notice the [0], it refers to the first fieldset element, if there were two and you wanted to append the new element in to the second you would use [1] (and [2] for the third and so forth). Also if the page only includes a single form and a single fieldset you could drop the first part (just so you can see how things are constructed)...
document.getElementsByTagName('fieldset')[0].appendChild(d);
2.) You'll usually want to use insertBefore...
var f = document.getElementById('form_id');
var element_parent = f.getElementsByTagName('fieldset')[0];
var element_before = f.getElementsByTagName('select')[0];
parent_element.insertBefore(d,element_before);
A little more information here...
https://developer.mozilla.org/en/insertBefore
NEVER EVER FOR ANY REASON USE INNERHTML!!! Lazy programmers use it all the time and fail to realize that it does NOT correctly register the DOM so elements associated with that proprietary Microsoft JScript method will NOT be seen when you try to work with them. For this reason alone you should avoid using frameworks such as jQuery as they jump to use the easiest things. Easy doesn't get the job done, easy makes the job look done long enough to make a single paycheck and then if you don't one day end up rewriting ALL of your code in that given area (long after you remember working with it and what you were trying to do) you'll be in a world of hurt.
PART THREE
JavaScript is an EVENT driven language, events are DOM based. The DOM and JavaScript are different things very closely tied together.
You can read more about DOM events here...
https://developer.mozilla.org/en/DOM/event
...and there is a good list of DOM events here...
http://en.wikipedia.org/wiki/DOM_events#HTML_events
In order to take advantage of the code you need to determine the event that best fits with your goal. Are you trying to do this when the form is submitted? That would be onsubmit. Are you trying to do this when the page loads? That would be onload.
Generally you can reuse events endlessly though you can only execute the onload event once.
If you visit my site and look at the JavaScript code you'll notice THREE things...
1.) An index.js file that is nothing but functions.
2.) An onload.js file with limited number of global variables (variables defined outside of a function) and the anonymous onload function.
Since you can only execute the onload event once if you want to do multiple things (e.g. execute multiple unrelated functions) you can use an anonymous function which is simply a function without a name...
window.onload = function()
{
my_func1();
my_func2();
my_func3();
}
Keep in mind that you should always keep script elements inside of the <head> element and not the <body> element otherwise it will lead you down a path of poor coding practices.
So if you create a standalone test file it may look something like this...
example.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test Page</title>
<script type="application/javascript">
//<![CDATA[
function form_days()
{
var d = document.getElementById('days');
var input_day = document.createElement('input');
input_day.setAttribute('id','days');
input_day.setAttribute('name','days');
input_day.setAttribute('type','text');
input_day.setAttribute('value',d.options[d.selectedIndex].text);
d.parentNode.insertBefore(input_day,d.nextSibling);
}
function get_methods(o)
{
var m = document.getElementById('dom_methods');
var dom_list = new Array();
for (i in o)
{
dom_list.push(i);
}
dom_list.sort();
for (var i=0; i<dom_list.length; i++)
{
m.value = m.value+dom_list[i]+'\n';
}
}
window.onload = function()
{
form_days();
get_methods(document.getElementById('days').options[document.getElementById('days').selectedIndex]);
}
//]]>
</script>
<style type="text/css">
label {border: #000 dotted 1px; padding: 0px 2px 0px 2px;}
label:hover {border: #000 solid 1px;}
textarea {height: 500px; width: 400px;}
</style>
</head>
<body>
<form action="http://www.test.com/school" method="post">
<fieldset>
<label for="days">Day:</label>
<select id="days" name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<div><textarea id="dom_methods"></textarea></div>
<div><input type="submit" value="submit" id="submitday" /></div>
</fieldset>
</form>
</body>
</html>
You should be able to copy-and-paste this to a file, name it example.xhtml. It's all functional, tested and working at the highest standards. Keep in mind that Internet Explorer 8 and older is not capable of XHTML (application/xhtml+xml) or comprehending the CORRECT media type/mime for JavaScript which is application/javascript so if you require backwards compatibility using text/javascript on script elements is not valid though will work.
well, you could change the values of the options, for example using jquery like this:
$('select[name=days] option').each(function(){
$(this).val($(this).html());
});​
http://jsfiddle.net/RCevC/
I think you're trying to update a text input when a user picks a selection from the dropdown? Try this:
html:
<select name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<input type="text" id="your_input" /> <!-- I added this field to your code -->
<input type="submit" value="submit" id="submitday"> ​
javascript (jquery)
$('select[name=days]').change(function(){
$('#your_input').val($(this).val());
});​
http://jsfiddle.net/z3peu/2/

Categories

Resources