How can IF and ELSE IF statements be used in JavaScript?

I am struggling to figure out the correct and efficient way to implement IF and else IF statements in javascript.

Here is my current challenge...

Currently, I am combining the values of 2 input fields and displaying them in another input field like this:

function FillIn() {
  document.getElementById('custom').value = 

'Main Text:' + ' ' +  document.getElementById('inputName').value + ', ' + '1st Text:' + ' ' + document.getElementById('inputName101').value

    ; 
}

The code mentioned above successfully puts the values of inputName and inputName101 into the custom input field.

Now, I have two radio buttons that I want to display their values in the custom input field based on the selected one.

Here is the code I am using for this purpose:

function FillIn() {
  document.getElementById('custom').value = 

    'Main Text:' + ' ' +  document.getElementById('inputName').value + ', ' + '1st Text:' + ' ' + document.getElementById('inputName101').value

if(document.getElementById('male').checked) {

   + ', ' + 'Type:' + ' ' + document.getElementById('male').value

}else if(document.getElementById('female').checked) {

     + ', ' + 'Type:' + ' ' + document.getElementById('female').value

}

; 
}

However, I am facing an issue as the radio button values are not showing up in the custom input field at all.

Any guidance or advice on how to resolve this would be greatly appreciated.

EDIT:

Below is the HTML for the radio buttons:

<input id="male" type="radio" name="gender" value="Road Legal" onclick="showhidediv(this);">  

<input id="female" type="radio" checked="checked" name="gender" value="Show Plate" onclick="showhidediv(this);">

Answer №1

It appears that the current approach is incorrect. It's not advisable to directly concatenate if/else conditions with strings. A more efficient way to structure your code would be:

function FillIn() {
    var str = 'Main Text: ';
    str += document.getElementById('inputName').value;
    str += ', 1st Text: ';
    str += document.getElementById('inputName101').value;

    if ( document.getElementById('male').checked ) {
        str += ', Type: ';
        str += document.getElementById('male').value;
    } else if ( document.getElementById('female').checked ) {
        str += ', Type: ';
        str += document.getElementById('female').value;
    }

    document.getElementById('custom').value = str;
}

Answer №2

Attempting to concatenate strings within and outside of if statements won't yield the desired result. It's crucial to follow this structure...

function FillIn() {
  document.getElementById('custom').value = 'Main Text:' + ' ' +  
    document.getElementById('inputName').value + ', ' + '1st Text:' + ' ' + 
    document.getElementById('inputName101').value;

  if (document.getElementById('male').checked) {
    document.getElementById('custom').value += ', ' + 'Type:' + ' ' +
      document.getElementById('male').value;
  }
  else if (document.getElementById('female').checked) {
    document.getElementById('custom').value += ', ' + 'Type:' + ' ' + 
      document.getElementById('female').value;
  }
}

It is highly likely that your code produced an error in the console. Reviewing those errors will help pinpoint what needs fixing.

Answer №3

It is not possible to incorporate an if statement directly into an expression. Despite this, your current implementation manages to execute; however, the logic within the if statement is simply evaluated and then discarded.

Instead of using an if statement, you can employ the conditional operator within an expression:

function FillIn() {
  document.getElementById('custom').value = 
    'Main Text:' + ' ' +  document.getElementById('inputName').value + ', ' +
    '1st Text:' + ' ' + document.getElementById('inputName101').value +
    (document.getElementById('male').checked ?
      ', ' + 'Type:' + ' ' + document.getElementById('male').value :
      (document.getElementById('female').checked ?
        ', ' + 'Type:' + ' ' + document.getElementById('female').value :
        ''
      )
    ); 
}

To enhance readability, utilizing local variables for the elements is recommended:

function FillIn() {
  var male = document.getElementById('male');
  var female = document.getElementById('female');
  document.getElementById('custom').value = 
    'Main Text:' + ' ' +  document.getElementById('inputName').value + ', ' +
    '1st Text:' + ' ' + document.getElementById('inputName101').value +
    (male.checked ?
      ', ' + 'Type:' + ' ' + male.value :
      (female.checked ?
        ', ' + 'Type:' + ' ' + female.value :
        ''
      )
    ); 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the Id from a TextField in MUI when the select property is activated?

I am struggling to retrieve the id from the mui TextFiled element when the select property is activated. However, I am always getting an undefined value. Here is the code snippet: export default ({ onChangeSelect, input, label, options, ...

What is the best way to turn off autocorrect in a textarea on IE11 without turning off spellcheck?

In my experience, disabling the spellcheck attribute seems to solve the auto-correct issue, but it also eliminates the underlining of misspelled words. <textarea id="TextArea1" spellcheck="false"></textarea> I prefer to keep spellcheck enabl ...

when webpack loads the bundle.js file, the mime type is converted to text/html

I'm currently working on implementing server side rendering for an application using react-redux and express for the server. We are also utilizing webpack to bundle our assets. To get started, I referred to the following documentation: https://redux ...

Utilizing JSON for live population of search filter results

I'm currently developing a search function for my website that will sift through a JSON Object using regular expressions. My goal is to have the results displayed in real time as the user types, similar to how Google shows search suggestions. However ...

Filtering in JavaScript arrays based on conditions that are not related to the elements in the array

Consider the following code snippet: var numbersArray = [1, 3, 6, 8, 11]; var returnedArray = numbersArray.filter(function(number) { const condition = false // or true sometimes return number > 7 && condition ; }); console.log(returnedArra ...

Troubleshooting error messages in the console during conversion of image URL to Base64 in AngularJS

While attempting to convert an image URL to Base64 using the FromImageUrl method, I encountered an error in my console. Access to the image located at '' from the origin 'http://localhost:8383' has been blocked due to CORS policy ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

Can a text file be loaded into the title of a Bootstrap tooltip?

Looking to dynamically load a text file into bootstrap tooltip titles. Here is a snippet of working code with hardcoded values: <div> <a id="A" type="button" class="btn btn-outline-secondary btn-lg" data-toggle=& ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

PersistJS callback function is malfunctioning

I stumbled upon a great library for managing client storage. You can find the latest version here: https://github.com/jeremydurham/persist-js However, I encountered an issue with the callback function. var result = store.get('saved_data', func ...

Tips for extracting data from a JSON using a variable

I'm currently facing an issue in extracting data from a JSON file. I have declared a variable and am attempting to use its value to retrieve information from the JSON. However, I seem to be encountering an error that I can't identify. let e = &qu ...

When a link with the href attribute set to "#" is clicked while using hammer.js, it will smoothly scroll the page

Recently, I've been using Hammer in my JavaScript to attach events. Take a look at the code snippet below: $('.get-stats').each(function() { Hammer(this).on('tap', function(e) { //my code window.location.href=" ...

Unable to access a user's public information using Instagram's API

I've spent the past week trying to create a simple Instagram preview application that should show a user's public data such as username, followers, following, and profile picture URL, but unfortunately, I haven't been able to find a solution ...

Tips for efficiently handling MongoDB data on the server side with socket management

My venture into using Socket.io for the first time has led me to create a simple game. At this point, I have a MongoDB database structured as follows: | Sessions | | Users | | Games | |-----------| |------------| |-----------| | * _id | ...

Steer clear of cross-domain solutions

Currently, I am developing a web application that allows customers to integrate it into their websites by linking to a JavaScript file on my server. Despite the application reading all JavaScript files from my server, I encounter an error when attempting t ...

How can I attach an event listener to each row in a table that is dynamically generated?

I am currently working on a table that is being populated using data from a JSON file. The number of entries in the JSON file can vary, resulting in different lengths for the table rows. Each row includes a bootstrap dropdown button with links for actions ...

Auto Suggest: How can I display all the attributes from a JSON object in the options list using material-ui (@mui) and emphasize the corresponding text in the selected option?

Currently, I am facing a requirement where I need to display both the name and email address in the options list. However, at the moment, I am only able to render one parameter. How can I modify my code to render all the options with both name and email? ...

Tips for showcasing nested information on the web page

Attempting to retrieve data from an API and insert it into the DOM In this case, the data is in the form of an array containing objects. Here's a sample of what the API displays in the console. https://i.sstatic.net/MLKya.png To access the array w ...

Developing an HTML table dynamically with JavaScript and incorporating CRM data

I am currently working on my JavaScript file, attempting to create an HTML table. Within this entity's record list are fields such as contractid, name, and address. var filter = "?$select=*&$filter=_plus_franchisee_value eq " + serviceProviderID ...

Is it possible for me to use any text as a JSON key?

Is it acceptable to use any utf-8 string as a property name in JSON? For example, is the following valid: var personData = { 'Matti Möttönen': { "FirstName": "Matti", "LastName": "Möttöne ...