How to set the value of an element using jquery and conditionally setting a manual value if the value is empty

Asked

Viewed 470 times

0

I have a form, which when submitted, sends data to a modal window. A part of the jquery I have, takes the value sent by the textbox with id "diagnose" and passes this value to the modal window, in a span tag with id "modal_diagnostico", as shown in the line below:

$("#modal_diagnostico"). text($("#diagnostico").val());

I need to pass a fixed text if the value of the texbox "diagnose" is empty (something like "Not informed"), and unfortunately I don’t know how to do that. Can you help me?

  • tried if(text($("#diagnostico"). val(). length !== 0){ $("#modal_diagnostico"). text($("#diagnostico"). val()); } Else { $("#modal_diagnostico"). text("TEST". val(); } but to no avail

1 answer

1


I’ll show you two techniques (of the countless) to do this, a traditional with if and Else

var texto = $("#diagnostico").val();
if(texto != "")
   $("#modal_diagnostico").text( texto );
else
   $("#modal_diagnostico").text( "Texto estático" );

Now ternary operators (which basically does the same thing in this example)

$("#modal_diagnostico").text( ($("#diagnostico").val()) ? $("#diagnostico").val() : "Texto estático" );

Browser other questions tagged

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