I’m relatively new to coding, and I need a bit of help with the if else functions.
I would like my website to check what is in a text input when the submit button is pressed, and then use the to() function to redirect the visitor, like this:
If textbox contains 01:
Redirect to page 01
If text box contains 02:
Redirect to page 2
etc. until page 25
If textbox contains something else:
Display error message
Does anyone know how this can be done?
It depends on what you really want to do, because there are a few ways to go about it.
I’m going to assume a few things:
- All pages are completely separate and predefined
- Each page’s path is sequential (page-1, page-2, …, page-25)
- You have three elements:
- Submit button
- Text input with id #textInput
- Error text with id #errorText
In the element inspector (bottom right) you set the onClick for the submit button element to be submit, then do the following:
import wixLocation from 'wix-location';
// This is your onClick event function for the submit button
export function submit(event) {
// This is the text input value
const input = $w("#textInput").value
// This is a regular expression to ensure
// everything in the string is a digit
const reg = /^\d+$/g
// If the string contains non-digits,
// show the error message
if (!reg.test(input)) {
$w("#errorText").text = "Error: Not a number"
$w("#errorText").show()
}
else {
// This turns 01 into 1, 02 into 2, ...
const pageNumber = parseInt(input)
// Checks if page number is in range
if (pageNumber >= 1 && pagenumber <= 25) {
// This is the path of the desired page
const path = "/page-" + pageNumber
// This redirects the user to the desired page
wixLocation.to(path)
}
else {
$w("#errorText").text = "Error: Out of range"
$w("#errorText").show()
}
}
}
Note: I have not fully tested this but it should work fine.
It says <, > and = can’t be used for strings and numbers. Is there any fix?\
if ( pageNumber >= 1 && pagenumber <= 25 ){
It says <, > and = can’t be used for strings and numbers. Is there any fix?\
if ( pageNumber >= 1 && pagenumber <= 25 ){
It says <, > and = can’t be used for strings and numbers. Is there any fix?\
if ( pageNumber >= 1 && pagenumber <= 25 ){
Fixed code, should work now