简体   繁体   中英

How can I grab just the text within a div, if it also includes some user entry via select and input boxes?

I'm making a little madlib game for my kids, but I'm having some trouble getting the text within the div, because of the select and input elements.

for example:

<div class='para1'>
This is a madlib game. 
Do you <select id='no1'>
<option selected>like</option>
<option> not like </option>
</select>
this kind of game? What would you rate it as, <input type="text">.
</div>

using $('.para1').text() gets me all the garbage in the select boxes; using $('para1').html() gets me the markup garbage.

I want the text of the selected option and any user input - along with thenew static text in the div - can this be done?

The final output should read: This is a madlib game. Do you like this kind of game? What would you rate it as, [input value here].

See example here: http://jsfiddle.net/4Fysw/

Here is a fiddle: http://jsfiddle.net/4Fysw/7/

As found on the jquery site about .text() it won't work on inputs or script tags, so in order to get what you are looking for I believe the only way is to make sure the format of the text supports an easy way of grabbing it, as I have done in the fiddle.

I basically wrap all the strings in <span> tags as they don't cause any forced styling by browser or css (of course unless you have default styling for span's), and they allow you to itterate over the children of the parent para1 element and determine if you should use the .val() function or just the normal .text() function to get the data to build up your string.

Hope this helps.

Update: Based on comment - here is a slightly refactored fiddle that supports a little more flexibility: http://jsfiddle.net/8QaFn/3/

Add the value attribute inside your option tags.

<option value="like">like</option>

And print it as:

$('#no1').val();

The textbox should have its own ID as well:

<input type="text" id="text1">

I updated your fiddle: http://jsfiddle.net/4Fysw/2/

This can help you.

$('#print').click(function(){
    var text1 = $('#no1').find(":selected").text();
    var text2 = $('.para1 input').val();
    $('#output').val(text1);
    $('#output2').val(text2);});

Working Demo: http://jsfiddle.net/4Fysw/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM