简单的javascript:数组和表单信息收集#2

时间:2016-02-13 00:55:59

标签: javascript html

我根本不了解javascript,我只是喜欢为自己制作列表。我目前正在尝试创建一个html页面,我可以跟踪我最喜欢的游戏中的角色,但我遇到了一些我不知道如何解决的问题。

<form name="inputNightlife" id="inputNightlife">
<h2>Nightlife</h2>
<label for="traits"><b>Traits:</b></label><br>
<select multiple="true" name="traits" id="traits">
        <option value="Cologne">Cologne</option>
        <option value="Stink">Stink</option>
        <option value="Fatness">Fatness</option>
        <option value="Fitness">Fitness</option>
    </select>
<label for="turnOns"><b>Turn Ons:</b></label><br>
<select multiple="true" name="turnOns" id="turnOns">
        <option value="Blonde Hair">Blonde Hair</option>
        <option value="Red Hair">Red Hair</option>
        <option value="Brown Hair">Brown Hair</option>
        <option value="Black Hair">Black Hair</option>
    </select>
    <p>Select all that apply.</p>
<nav id="box8" class="hide"><table id="menu3"><tr><td rowspan="2" id="soft">
<textarea name="source8" onclick="this.focus();this.select()" cols="40" rows="3" id="result">
</textarea></td><td>
<input type="button" value="Get Code!" onclick="javascript:generateNightlife();"></td>
<td rowspan="2" id="softA">
<img src="./forSCV/icons/nightlife.png" alt="Nightlife" title="Nightlife" id="arrow" onclick="toggle('box8');">
</td></tr><tr><td>
<input type="button" value="Test Code" onclick="javascript:displayNightlife(this.form);">
</td></tr></table></nav></form>

单击按钮时,文档区域中将显示document.results.endresults.value。然后我可以复制结果,并将它们保存为html。这是一个页面生成器(我能想到的最好的)。

我不确定如何使traits和turnOns自动创建所选选项的数组(带空格),然后将在document.result.endresult.value中打印。我确实找到了几种不同的方法来从表单创建一个数组,但不是如何让它进入document.result.endresult.value。

单程Google。另一种方式Google

...添加

好的,我重写了我的html以包含名称和id,我发现了一个更好的页面生成器,所以我试图让它工作。现在我试过了。

function byId(idStr){return document.getElementById(idStr);}

function getFormValues() {
var traitsSelectElem = byId('traits');
var turnOnsSelectElem = byId('turnOns');
var chosenTraits = getSelectedOptions(traitsSelectElem);
var chosenTurnOns = getSelectedOptions(turnOnsSelectElem);
var i, n, outputStr;
n = chosenTraits.length;
outputStr = '';
for (i = 0; i < n; i ++)
{
    if (outputStr != ".")
        outputStr += ", ";
    outputStr += chosenTraits[i].value;
}
byId('traitsOutput').innerText = outputStr;

n = chosenTurnOns.length;
outputStr = '';
for (i = 0; i < n; i++)
{
    if (outputStr != '.')
        outputStr += ', ';
    outputStr += chosenTurnOns[i].value;
}
byId('turnOnsOutput').innerText = outputStr;
}
function getSelectedOptions(selectElem) {
var i, nOptions = selectElem.options.length;
var result = [];
for (i = 0; i < nOptions; i++)
{
    if (selectElem.options[i].selected)
    {
        result.push(
                        {
                            value: selectElem.option[i].value
                        }
                    );
    }
}
return result;
}

function generateNightlife() {

//nightlife
var traits = getFormValues();
var turnOns = getFormValues();
turnOff = document.inputNightlife.turnOff.value;
perfumeDuration = document.inputNightlife.perfumeDuration.value;
lovePotion = document.inputNightlife.lovePotion.value;

outputNightlife = "<a name='nightlife'></a>\n<div id='easy'>\n<h2>Nightlife</h2>\n
<table class='ntlf'><tr><th>Traits:</th><td class='white'>"+traits+"
</td></tr><tr><th>Turn Ons:</th><td class='white'>"+turnOnsOutput+"</td></tr><tr><th>
Turn Offs:</th><td class='white'>"+turnOff+"</td></tr></table>\n<p class='up2'>Perfume 
Duration: <span class='colorme'>"+perfumeDuration+"</span></p>\n<p>Love Potion Duration: 
<span class='colorme'>"+lovePotion+"</span></p>\n</div>\n"

document.inputNightlife.source8.value = outputNightlife;

return outputNightlife;
}

当我用chrome测试时,它说它不能设置null的.innerText的属性,我认为是因为我不希望它转到div。我希望将值返回到函数generateNightlife,以便可以将其添加到outputNightlife。我不知道该怎么做,我需要一些帮助。

1 个答案:

答案 0 :(得分:1)

这是一个完全有效的示例,它将从select元素中提取多个选择,然后继续使用它们构建数组,最后将它们打印到屏幕上。

你链接到的两个tutes中的任何一个都没关系 - 总是很难知道什么是显而易见的,需要解释什么以及什么将依赖于可能/可能没有涵盖的背景信息。

我在这里使用了一些不同的技巧,有许多更复杂的我选择避开。我希望这些评论能够使操作更加清晰,但我们很乐意根据需要添加说明。 :)

这是一个可运行的代码段:

function byId(idStr){return document.getElementById(idStr);}

function getFormValues()
{
	// 1. get a reference to each of the select elemenets we wish to process
	var mainMealSelectElem = byId('mainSelect');
	var dessertSelectElem = byId('dessertSelect');

	// 2. get an array of all of the selected options in each of our select elements
	var chosenMains = getSelectedOptions(mainMealSelectElem);
	var chosenSweets = getSelectedOptions(dessertSelectElem);
	
	var i, n, outputStr;
	n = chosenMains.length;
	outputStr = '';
	for (i=0; i<n; i++)
	{
		// only add a comma before an element if at least one element already exists
		// this is how we do it when writing a list manually.
		if (outputStr != '')
			outputStr += ", ";
			
		// grab the two values from the array we constructed using the getSelectedOptions function.
		// we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
		// whatever we named them in the below function is what we need to use to access them here.
		outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
	}
	// set the text content of the target span with the array of chosen stuff.
	byId('mainsOutput').innerText = outputStr;

	
	n = chosenSweets.length;
	outputStr = '';
	for (i=0; i<n; i++)
	{
		if (outputStr != '')
			outputStr += ", ";
		outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
	}
	byId('dessertsOutput').innerText = outputStr;
}

// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
	// aloop counter and the total number of iterations required
	var i, nOptions = selectElem.options.length;
	
	// the empty result array
	var result = [];
	
	// loop through all the options this select element has
	for (i=0; i<nOptions; i++)
	{
		// if the current option is selected, we'll need to extract it's info and add it to the output array
		if (selectElem.options[i].selected)
		{
			result.push( 
							{
								value: selectElem.options[i].value, 
								textLabel: selectElem.options[i].label
							}
						);
		}
	}
	return result;
}
div
{
	display: inline-block;
}
.centered
{
	text-align: center;
}
<div class='centered'>
		<form>
			<h2>Select the ones you like</h2>
			<select id='mainSelect' multiple>
				<option value='spag'>Spaghetti</option>
				<option value='satay'>Peanut satay</option>
				<option value='schnitz'>Chicken Schnitzel</option>
			</select>
			<select id='dessertSelect' multiple>
				<option value='1'>Ice-cream</option>
				<option value='2'>Fruit salad</option>
				<option value='3'>Custard</option>
			</select>
		</form>
		<br>
		<button onclick='getFormValues()'>Get chosen values</button>
		<hr>
	</div>
	<br>
	<div>
		Selected main-meals: <span id='mainsOutput'></span><br>
		Selected desserts: <span id='dessertsOutput'></span><br>
	</div>

这是完整的(复制/可管理的)来源:

<!doctype html>
<html>
<head>
<script>
function byId(idStr){return document.getElementById(idStr);}

function getFormValues()
{
    // 1. get a reference to each of the select elemenets we wish to process
    var mainMealSelectElem = byId('mainSelect');
    var dessertSelectElem = byId('dessertSelect');

    // 2. get an array of all of the selected options in each of our select elements
    var chosenMains = getSelectedOptions(mainMealSelectElem);
    var chosenSweets = getSelectedOptions(dessertSelectElem);

    var i, n, outputStr;
    n = chosenMains.length;
    outputStr = '';
    for (i=0; i<n; i++)
    {
        // only add a comma before an element if at least one element already exists
        // this is how we do it when writing a list manually.
        if (outputStr != '')
            outputStr += ", ";

        // grab the two values from the array we constructed using the getSelectedOptions function.
        // we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
        // whatever we named them in the below function is what we need to use to access them here.
        outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
    }
    // set the text content of the target span with the array of chosen stuff.
    byId('mainsOutput').innerText = outputStr;


    n = chosenSweets.length;
    outputStr = '';
    for (i=0; i<n; i++)
    {
        if (outputStr != '')
            outputStr += ", ";
        outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
    }
    byId('dessertsOutput').innerText = outputStr;
}

// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
    // aloop counter and the total number of iterations required
    var i, nOptions = selectElem.options.length;

    // the empty result array
    var result = [];

    // loop through all the options this select element has
    for (i=0; i<nOptions; i++)
    {
        // if the current option is selected, we'll need to extract it's info and add it to the output array
        if (selectElem.options[i].selected)
        {
            result.push( 
                            {
                                value: selectElem.options[i].value, 
                                textLabel: selectElem.options[i].label
                            }
                        );
        }
    }
    return result;
}
</script>
<style>
div
{
    display: inline-block;
}
.centered
{
    text-align: center;
}
</style>
</head>
<body>
    <div class='centered'>
        <form>
            <h2>Select the ones you like</h2>
            <select id='mainSelect' multiple>
                <option value='spag'>Spaghetti</option>
                <option value='satay'>Peanut satay</option>
                <option value='schnitz'>Chicken Schnitzel</option>
            </select>
            <select id='dessertSelect' multiple>
                <option value='1'>Ice-cream</option>
                <option value='2'>Fruit salad</option>
                <option value='3'>Custard</option>
            </select>
        </form>
        <br>
        <button onclick='getFormValues()'>Get chosen values</button>
        <hr>
    </div>
    <br>
    <div>
        Selected main-meals: <span id='mainsOutput'></span><br>
        Selected desserts: <span id='dessertsOutput'></span><br>
    </div>
</body>
</html>