简体   繁体   中英

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle

For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?

For example, I would like it to output: "AND name: john EXCEPT number 222".

I would also like to be able click on a result to remove it, and clear the field. Thank you

$(".allS").change(function () {
    if ($(this).next('.textArea').not(':empty'))
    // varible to hold string
    var str = "";
    $("select option:selected").each(function () {
        str += $(this).text() + " ";
    });
    $("#text_here").text(str);
}).change();

$('.textArea').change(function(){

    var $inputs = $('form#form :input[type="text"]'),
        result = "";

    $inputs.each(function(){
        // access the individual input as jQuery object via $(this)
        result += $(this).val()+"<br>";
    });

    // store result in some div
    $('div#text_here').text(result);
}).change();

There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle .

$(".allS, .textArea").change(function () {
    var str = '';
    if ($('#name').val().length > 0 && $('#number').val().length > 0)
        var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();

    $("#text_here").html(str);
});

Basically, what this does is attach a change event handler to both classes ( .alls, .textArea ), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.

Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.

This may or may not be what you want (I think it is, from looking at your html):

'form#form input[type=text]'

Also your <br> 's are not working because you called text() . call html() instead.

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