Questions javascript [closed]

-3

I'm having trouble solving these exercises if they could help ... Here is the code:

<form name="myForm">
    <label>Radio station name
        <input type="text" name="name" />
    </label>
    <select name="music_type">
        <option value="rock" selected>Rock</option>
        <option value="pop">Pop</option>
        <option value="jazz">Jazz</option>
    </select>
    <button onclick="saveForm()">Submit</button>
</form>

And the questions are:

  • How to write a Javascript function that stores the input values of form in session storage , when the user clicks the Submit button?

  • What should I change in the previous function, using jQuery, so that when the button is clicked, the background of form is changed to gray?

asked by anonymous 01.07.2015 / 11:58

1 answer

4

I will not solve your exercise, but I can explain what you need to think about to solve it.

When you have a <form> with a button (and note that when button does not have the type="" attribute it defaults type="submit" ), pressing the button will send the form data and refresh to the page.

As you have onclick="saveForm()" this will make a function called saveForm run that has to be in global scope. You can read here what it means. .

Within this function you must write to localStorage . There are lots of questions here in the SOAP about localStorage , so you'll know more if it's not clear.

You have to keep in mind that localStorage saves strings . In other words, you have to serialize the data before inserting it. You can do this with JSON.stringify(teusDados) ;

How to fetch the data?

Do your elements have a name attribute right? then you can use var select = document.querySelector('[name="music_type"]'); in the case of select, and the same as input . To save your value, just do var valorSelect = select.value; .

How to assemble the data?

You can do an object for example like this:

var teusDados = {
    select: select.value,
    input: input.value
};

and then use this in JSON.stringify as I mentioned above.

Regarding the second question I think it is advanced to the knowledge that you have today. You need to know what jQuery is and how it gets arguments and turns them into objects with jQuery methods. That's a lot to mention here. But the steps you have to do use these methods:

$(botão) // tens de passar o elemento <button> para o jQuery, provavelmente vais queres usar um seletor CSS: 'button'
    .closest('form') // para selecionares o ancestral/pai mais próximo que seja uma <form>
    .css(attributo, valor)

The syntax of .css() is (atributo, valor) . You will want to use background-color and gray color there.

Good luck!

    
01.07.2015 / 12:35