In the previous lesson, we covered how to grab user input from a TextBox using a button click event.
1. Update Model With User Input
Now what we would like to do is to use the text entered in the text field to update the a field in the model. I’ll call this field score.
So let’s follow the steps
Step 1 – Change the init method to include two more fields in the model like so:
init = {value = 877, firstName = "Kindson", score = 99}
Step 2 – Import the toInt() function from String in the import section. This is because, we expect a number to be input.
Step 3 – We now want to update the score when the TextChanged message is called. So we’ll modify the case section of our update method by using the | operator to assign a new score to the model but keeping the model unchanged as we learnt earlier.
case msg of Add -> {model | value = 20} TextChanged newText -> {model | score = toInt newText}
What is happening here is that we are converting the newText to using toInt function and assigning the result to the score.
The problem here is that toInt() returns a a type ‘maybe’ while score if of type number.
2. Custom Function to Handle Input
Now the user input from the TextBox when converted using toInt() return ‘maybe’ and the maybe could be either:
just val – this is returned when the conversion is successfully and the number equivalent (val) of the argument is returned.
Nothing – this is returned when the toInt() fails. For example, you try to convert “abc” to number using toInt()
Therefore in this custom function we will write, will simply return 0 when Nothing is returned by the toInt() function.
Our custom function is given below. I call it parseInput()
parseInput text = let theMaybe = toInt text in case theMaybe of Just val -> val Nothing -> 0
Now we can use out custom function in the update method like so
TextChanged newText -> {model | score = parseInput newText}
Finally we’ll modify the Add function to add the user input number to the model value. You can do this like so
Add -> {model | value = model.value + model.score}
Now you can go ahead to recompile the program. You will notice that when you click the button, the value in the TextBox is continually added to the score and displayed.