Disable part of the form by Jquery

Asked

Viewed 191 times

1

I don’t have much experience with Jquery and Ajax.

I am developing a form that when selecting the Radio Button to send anonymous information, it should make invisible the part of the form that refers to the address.

I’m using HTML5, CSS3, Bootstrap, PHP.

  • Could put the code already developed.

  • 1

    Check out the guide [Ask]. If by chance you read English, here is a great article on how to improve our write questions.

2 answers

2


Hello!

You can use the function .Hide() along with .change() jQuery.

$("input[name='opcoes']").change(function () {
    if ($(this).val() === 'Sim') {
        $("#painelEndereco").fadeIn();
    } else {
        $("#painelEndereco").fadeOut(function() {
            $(this).remove();
        });
    }
});

The complete example you can find here: http://jsfiddle.net/vrcca/fC7Yb/

Edit 1: Added the suggestions of Rodrigoborth.

Abs!

  • 1

    this method is functional, but could be done with ajax to replace the content completely without leaving a possible security "failure"... also recommend replacing the show and the Hide by fadein and fadeOut respectively, it is more beautiful :D

  • Thank you all. I’ll take the example of vrcca. Thank you very much.

  • Just one more thing. Where do I put the Jquery code? Thanks.

  • within $(Document).ready. Here is an example of the jQuery documentation: http://learn.jquery.com/about-jquery/how-jquery-works/#complete-example

2

I recommend the use of checkbox to say whether it is anonymous or not:

Javascript:

$(function() {
    var $check = $("#checkAnonimo");
    $check.on("change", function () {
        var anonimo = $check.is(":checked");
        anonimo ? $("#camposAnonimo").hide() : $("#camposAnonimo").show();
        $("#camposAnonimo input").prop("disabled", anonimo);
    });
});

Note that in addition to hiding address-related inputs, I also disable them, because even hidden, if you submit the form, the data will be sent if they have been filled in previously.

Html:

<form action="" method="POST">
    <div><label for="textOpiniao">Escreva sua opinião:<br/></label><textarea id="textOpiniao">Sua opinião aqui!</textarea></div>
    <label for="checkAnonimo"><input type="checkbox" id="checkAnonimo"/> Anônimo?</label>
    <div id="camposAnonimo">
        <div><label for="textNome">Nome: <input type="text" name="nome" id="textNome"/></label></div>
        <div><label for="textEndereco">Endereço: <input type="text" name="endereco" id="textEndereco"/></label></div>
    </div>
    <div><input type="submit" value="Enviar"/></div>
</form>
  • Thank you all. It’s working perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.