ghostrider
ghostrider

Reputation: 1

How to customise web-notifications?

I want to send web-notifications with my own input and decide when I send it (e.g. submitting a form). I'm making this for non-coding experienced people, so I'm looking for a simple interface

I'm trying to make a web notifications system from a form. This way I can decide when and what message the notification will be displaying. My current code is not working:

(Note: I have already asked for permission to display notifications!)

Form

<form id='form' >
<label for='userInput' class='alert-title'>Notifications</label><br>
<div class='lijn3'></div>
<label for='userInput'>Make a new notification</label><br>
<label for='userInput'>Title</label><br>
<input  type='text' id='userInput' /><br>
  <label for='userText'>Text</label><br>
 <input  type='text' id='userText' /><br>
  <input  type='submit' onclick='createNotification();' />
</form>

<script>
function createNotification() {
    var title = document.getElementById("userInput").value;
    var text = document.getElementById("userText").value;
    var image = '/style/afbeeldingen/profielfoto.png';
    console.log(title,text)
    var no = new Notification(title, { body: text, icon: img });
}
</script>

When I submit the form, I don't get a notification. Instead, it is refreshing the page. What is wrong in my code or how should I approach this? Any working (alternative, maybe without a form?) solution is welcome!

This is my first question. Please tell me if you don't understand the question or correct me:)

Upvotes: 0

Views: 583

Answers (1)

A. Meshu
A. Meshu

Reputation: 4148

You need to disable form submit. The quicker way to handle this would be change this line:

<input  type='submit' onclick='createNotification();' />

To this:

<input  type='button' onclick='createNotification();' />

Snippet:

function createNotification() {
    var title = document.getElementById("userInput").value;
    var text = document.getElementById("userText").value;
    var image = '/style/afbeeldingen/profielfoto.png';
    console.log(title,text)
    var no = new Notification(title, { body: text, icon: image });
}
<form id='form' >
<label for='userInput' class='alert-title'>Notifications</label><br>
<div class='lijn3'></div>
<label for='userInput'>Make a new notification</label><br>
<label for='userInput'>Title</label><br>
<input  type='text' id='userInput' /><br>
  <label for='userText'>Text</label><br>
 <input  type='text' id='userText' /><br>
  <input  type='button' onclick='createNotification();' />
</form>

Plus: you need to change img to image as your variable name. So this: var no = new Notification(title, { body: text, icon: img }); Should be this: var no = new Notification(title, { body: text, icon: image });

Upvotes: 1

Related Questions