Skip to content
- Courses
- DSA to Development
- Newly Launched!
- For Working Professionals
- For Students
- GATE Exam Courses
- All Courses
- Tutorials
- Data Structures & Algorithms
- DSA for Beginners
- Data Structures
- Algorithms
- Complete DSA Tutorial
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top 100 DSA Interview Questions Topic-wise
- 100 Days of Code
- Python
- ML & Data Science
- Machine Learning
- Data Science Tutorial
- Data Science Packages
- Data Visualization
- Data Analysis
- Deep Learning
- NLP Tutorial
- OpenCV Tutorial
- Interview Questions
- System Design
- Interview Corner
- Languages
- Web Development
- HTML
- CSS
- JavaScript
- TypeScript
- ReactJS
- Node.js
- PHP
- AngularJS
- jQuery
- Web Development Using Python
- Web Design
- 100 Days of Web Development
- CS Subjects
- DevOps And Linux
- School Learning
- GATE
- GeeksforGeeks Videos
- Data Structures & Algorithms
- Jobs
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Contests
-
- DSA Course
- DSA
- Practice Searching Algorithms
- MCQs on Searching Algorithms
- Tutorial on Searching Algorithms
- Linear Search
- Binary Search
- Ternary Search
- Jump Search
- Sentinel Linear Search
- Interpolation Search
- Exponential Search
- Fibonacci Search
- Ubiquitous Binary Search
- Linear Search Vs Binary Search
- Interpolation Search Vs Binary Search
- Binary Search Vs Ternary Search
- Sentinel Linear Search Vs Linear Search
Last Updated : 23 Nov, 2023
Summarize
Comments
Improve
Given an alphanumeric string S of length N, the task is to check if the given string represents a hexadecimal number or not. Print Yes if it represents a hexadecimal number. Otherwise, print No.
Examples:
Input: S = “BF57C”
Output: Yes
Explanation:
Decimal Representation of the given string = 783740Input: S = “58GK”
Output: NoApproach: The approach is based on the idea that all the elements of a hexadecimal number lie between characters A to F or between integers 0 to 9. Below are the steps to solve the problem:
- Iterate over the given string.
- Check if each character of the string is between characters A to F or between 0 and 9.
- If found to be true, then print Yes.
- Otherwise, print No.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using
namespace
std;
// Function to check if the string
// represents a hexadecimal number
void
checkHex(string s)
{
// Size of string
int
n = s.length();
// Iterate over string
for
(
int
i = 0; i < n; i++)
{
char
ch = s[i];
// Check if the character
// is invalid
if
((ch <
'0'
|| ch >
'9'
) &&
(ch <
'A'
|| ch >
'F'
))
{
cout <<
"No"
<< endl;
return
;
}
}
// Print true if all
// characters are valid
cout <<
"Yes"
<< endl;
}
// Driver code
int
main()
{
// Given string
string s =
"BF57C"
;
// Function call
checkHex(s);
return
0;
}
// This code is contributed by divyeshrabadiya07
Java
// Java implementation of the above approach
import
java.util.*;
import
java.io.*;
class
GFG {
// Function to check if the string
// represents a hexadecimal number
public
static
void
checkHex(String s)
{
// Size of string
int
n = s.length();
// Iterate over string
for
(
int
i =
0
; i < n; i++) {
char
ch = s.charAt(i);
// Check if the character
// is invalid
if
((ch <
'0'
|| ch >
'9'
)
&& (ch <
'A'
|| ch >
'F'
)) {
System.out.println(
"No"
);
return
;
}
}
// Print true if all
// characters are valid
System.out.println(
"Yes"
);
}
// Driver Code
public
static
void
main(String[] args)
{
// Given string
String s =
"BF57C"
;
// Function Call
checkHex(s);
}
}
Python3
# Python3 implementation of the
# above approach
# Function to check if the string
# represents a hexadecimal number
def
checkHex(s):
# Iterate over string
for
ch
in
s:
# Check if the character
# is invalid
See AlsoC Library -- GeeksforGeeks isxdigit - cppreference.comstrcmp, wcscmp, _mbscmp, _mbscmp_lHexadecimal in C | Functions of Hexadecimal in C Programming Languageif
((ch <
'0'
or
ch >
'9'
)
and
(ch <
'A'
or
ch >
'F'
)):
print
(
"No"
)
return
# Print true if all
# characters are valid
print
(
"Yes"
)
# Driver Code
# Given string
s
=
"BF57C"
# Function call
checkHex(s)
# This code is contributed by extragornax
C#
// C# implementation of
// the above approach
using
System;
class
GFG{
// Function to check if the string
// represents a hexadecimal number
public
static
void
checkHex(String s)
{
// Size of string
int
n = s.Length;
// Iterate over string
for
(
int
i = 0; i < n; i++)
{
char
ch = s[i];
// Check if the character
// is invalid
if
((ch <
'0'
|| ch >
'9'
) &&
(ch <
'A'
|| ch >
'F'
))
{
Console.WriteLine(
"No"
);
return
;
}
}
// Print true if all
// characters are valid
Console.WriteLine(
"Yes"
);
}
// Driver Code
public
static
void
Main(String[] args)
{
// Given string
String s =
"BF57C"
;
// Function Call
checkHex(s);
}
}
// This code is contributed by gauravrajput1
Javascript
<script>
// JavaScript implementation of the
// above approach
// Function to check if the string
// represents a hexadecimal number
function
checkHex(s)
{
// Size of string
let n = s.length;
// Iterate over string
for
(let i = 0; i < n; i++)
{
let ch = s[i];
// Check if the character
// is invalid
if
((ch <
'0'
|| ch >
'9'
) &&
(ch <
'A'
|| ch >
'F'
))
{
document.write(
"No"
);
return
;
}
}
// Print true if all
// characters are valid
document.write(
"Yes"
);
}
// Driver code
// Given string
let s =
"BF57C"
;
// Function Call
checkHex(s);
// This code is contributed by souravghosh0416
</script>
Output
Yes
Time Complexity: O(N)
Auxiliary Space: O(1)Approach 2:
Approach:
We can use the built-in function int() with a base of 16 to convert the string to a hexadecimal number. If the conversion is successful, the input string represents a hexadecimal number.
- The input string s is passed as a parameter to the function.
- The int() function is called with the input string s and a base of 16 as its parameters. This function converts a string representation of a number into an integer.
- If the conversion is successful, the function returns True, indicating that the input string represents a hexadecimal number.
- If the conversion raises a ValueError, the function returns False, indicating that the input string does not represent a hexadecimal number. The ValueError is raised when the input string contains characters that are not valid hexadecimal digits.
C++
#include <iostream>
#include <string>
#include <sstream>
bool
isHexadecimal(
const
std::string& s) {
try
{
// Attempt to parse the string as an integer in base 16 (hexadecimal)
std::istringstream stream(s);
unsigned
int
value;
stream >> std::hex >> value;
return
!stream.fail();
// If successful, the string is hexadecimal
}
catch
(std::exception& e) {
return
false
;
// If an exception is caught, the string is not hexadecimal
}
}
int
main() {
std::string s1 =
"BF57C"
;
if
(isHexadecimal(s1)) {
std::cout <<
"Yes"
<< std::endl;
std::istringstream stream(s1);
unsigned
int
value;
stream >> std::hex >> value;
std::cout <<
"Decimal Representation of the given string = "
<< value << std::endl;
}
else
{
std::cout <<
"No"
<< std::endl;
}
std::string s2 =
"58GK"
;
if
(isHexadecimal(s2)) {
std::cout <<
"Yes"
<< std::endl;
std::istringstream stream(s2);
unsigned
int
value;
stream >> std::hex >> value;
std::cout <<
"Decimal Representation of the given string = "
<< value << std::endl;
}
else
{
std::cout <<
"No"
<< std::endl;
}
return
0;
}
Java
public
class
HexadecimalValidator {
// Function to check if a string is a valid hexadecimal representation
public
static
boolean
isHexadecimal(String s) {
try
{
// Attempt to parse the string as an integer in base 16 (hexadecimal)
Integer.parseInt(s,
16
);
return
true
;
// If successful, the string is hexadecimal
}
catch
(NumberFormatException e) {
return
false
;
// If an exception is caught, the string is not hexadecimal
}
}
public
static
void
main(String[] args) {
String s1 =
"BF57C"
;
if
(isHexadecimal(s1)) {
System.out.println(
"Yes"
);
System.out.println(
"Decimal Representation of the given string = "
+ Integer.parseInt(s1,
16
));
}
else
{
System.out.println(
"No"
);
}
String s2 =
"58GK"
;
if
(isHexadecimal(s2)) {
System.out.println(
"Yes"
);
System.out.println(
"Decimal Representation of the given string = "
+ Integer.parseInt(s2,
16
));
}
else
{
System.out.println(
"No"
);
}
}
}
Python3
def
is_hexadecimal_1(s):
try
:
int
(s,
16
)
return
True
except
ValueError:
return
False
s1
=
"BF57C"
if
is_hexadecimal_1(s1):
print
(
"Yes"
)
print
(
"Decimal Representation of the given string = {}"
.
format
(
int
(s1,
16
)))
else
:
print
(
"No"
)
s2
=
"58GK"
if
is_hexadecimal_1(s2):
print
(
"Yes"
)
print
(
"Decimal Representation of the given string = {}"
.
format
(
int
(s2,
16
)))
else
:
print
(
"No"
)
C#
// C# code for the above approach
using
System;
public
class
GFG {
// Function to check if a string is in hexadecimal
// format
public
static
bool
IsHexadecimal(
string
s)
{
try
{
// Attempt to parse the string as an integer in
// base 16 (hexadecimal)
_ = Convert.ToInt32(s, 16);
return
true
;
// If successful, the string is
// hexadecimal
}
catch
(Exception) {
return
false
;
// If an exception is caught, the
// string is not hexadecimal
}
}
// Main method
public
static
void
Main(
string
[] args)
{
string
s1 =
"BF57C"
;
if
(IsHexadecimal(s1)) {
Console.WriteLine(
"Yes"
);
int
value = Convert.ToInt32(s1, 16);
Console.WriteLine(
"Decimal Representation of the given string = "
+ value);
}
else
{
Console.WriteLine(
"No"
);
}
string
s2 =
"58GK"
;
if
(IsHexadecimal(s2)) {
Console.WriteLine(
"Yes"
);
int
value = Convert.ToInt32(s2, 16);
Console.WriteLine(
"Decimal Representation of the given string = "
+ value);
}
else
{
Console.WriteLine(
"No"
);
}
}
}
// This code is contributed by Susobhan Akhuli
Javascript
function
isHexadecimal(s) {
try
{
// Attempt to parse the string as an integer in base 16 (hexadecimal)
let value = parseInt(s, 16);
return
!isNaN(value);
// If successful, the string is hexadecimal
}
catch
(e) {
return
false
;
// If an exception is caught, the string is not hexadecimal
}
}
let s1 =
"BF57C"
;
if
(isHexadecimal(s1)) {
console.log(
"Yes"
);
let value = parseInt(s1, 16);
console.log(
"Decimal Representation of the given string ="
, value);
}
else
{
console.log(
"No"
);
}
let s2 =
"58GK"
;
if
(isHexadecimal(s2)) {
console.log(
"Yes"
);
let value = parseInt(s2, 16);
console.log(
"Decimal Representation of the given string ="
, value);
}
else
{
console.log(
"No"
);
}
Output
YesDecimal Representation of the given string = 783740No
Time Complexity: O(n)
Space Complexity: O(1)
Please Login to comment...
Similar Reads
Check whether Array represents a Fibonacci Series or not
Given an array arr[] consisting of N integers, the task is to check whether a Fibonacci series can be formed using all the array elements or not. If possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = { 8, 3, 5, 13 } Output: Yes Explanation: Rearrange given array as {3, 5, 8, 13} and these numbers form Fibonacci series. Input: ar
9 min read
Check if an array represents Inorder of Binary Search tree or not
Given an array of N element. The task is to check if it is Inorder traversal of any Binary Search Tree or not. Print "Yes" if it is Inorder traversal of any Binary Search Tree else print "No". Examples: Input : arr[] = { 19, 23, 25, 30, 45 } Output : Yes Input : arr[] = { 19, 23, 30, 25, 45 } Output : NoRecommended PracticeInorder Traversal and BST
5 min read
Check if an encoding represents a unique binary string
Given an encoding of a binary string of length k, the task is to find if the given encoding uniquely identifies a binary string or not. The encoding has counts of contiguous 1s (separated by 0s). For example, encoding of 11111 is {5}, encoding of 01101010 is {2, 1, 1} and encoding of 111011 is {3, 2}. Examples : Input: encoding[] = {3, 3, 3} Length
6 min read
Check if a given string is a valid Hexadecimal Color Code or not
Given a string str, the task is to check whether the given string is an HTML Hex Color Code or not. Print Yes if it is, otherwise print No. Examples: Input: str = “#1AFFa1”Output: Yes Input: str = “#F00”Output: Yes Input: str = �”Output: No Approach: An HTML Hex Color Code follows the below-mentioned set of rules: It starts with the ‘#’ symbol.Then
7 min read
Check if the given graph represents a Bus Topology
Given a graph G, check if it represents a Bus Topology.A Bus Topology is the one shown in the image below: Examples: Input: Output: YES Input: Output: NO A graph of V vertices represents a bus topology if it satisfies the following two conditions: Each node except the starting end ending ones has degree 2 while the starting and ending have degree 1
12 min read
Check if the given graph represents a Star Topology
Given a graph G, the task is to check if it represents a Star Topology.A Star Topology is the one shown in the image below: Examples: Input : Graph = Output : YES Input : Graph = Output : NO A graph of V vertices represents a star topology if it satisfies the following three conditions: One node (also called the central node) has degree V - 1.All n
15+ min read
Check if the given graph represents a Ring Topology
Given a graph G, the task is to check if it represents a Ring Topology.A Ring Topology is the one shown in the image below: Examples: Input : Graph = Output : YES Input : Graph = Output : NO A graph of V vertices represents a Ring topology if it satisfies the following three conditions: Number of vertices >= 3.All vertices should have degree 2.N
11 min read
Check if given path between two nodes of a graph represents a shortest paths
Given an unweighted directed graph and Q queries consisting of sequences of traversal between two nodes of the graph, the task is to find out if the sequences represent one of the shortest paths between the two nodes.Examples: Input: 1 2 3 4 Output: NOExplanation: The first and last node of the input sequence is 1 and 4 respectively. The shortest p
8 min read
How to check if a given array represents a Binary Heap?
Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: arr[] = {9, 15, 10, 7, 12, 11} Output: False The giv
11 min read
Smallest string without any multiplication sign that represents the product of two given numbers
Given two numbers A and B, the task is to print the string of the smallest possible length which evaluates to the product of the two given numbers i.e., A*B, without using the multiplication sign. Any perfect power of 2 can be expressed in the form of a left-shift operator. For Example: N = 2 = 1<<1 = "<<1" N = 4 = 1<<2 = "<
9 min read
Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
S(r, n), represents the number of ways that we can arrange r objects around indistinguishable circles of length n, and every circle n must have at least one object around it. Examples: Input: r = 9, n = 2Output: 109584Input: r = 6, n = 3Output: 225The special cases are: S(r, 0) = 0, trivial.S(r, 1) represents the circular permutation which is equal
15+ min read
Check if a HexaDecimal number is Even or Odd
Given a HexaDecimal number, check whether it is even or odd.Examples: Input: N = ABC7787CC87AA Output: Even Input: N = 9322DEFCD Output: Odd Naive Approach: Convert the number from Hexadecimal base to Decimal base.Then check if the number is even or odd, which can be easily checked by dividing by 2. Time Complexity: O(N)Efficient approach: Since He
4 min read
Convert Hexadecimal value String to ASCII value String
Given the Hexadecimal value string as input, the task is to convert the given hexadecimal value string into its corresponding ASCII format string. Examples: Input: 6765656b73Output: geeks Input: 6176656e67657273Output: avengers The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. Being a Base-16 system, there are 16 possi
6 min read
Sorted order printing of a given array that represents a BST
Given an array that stores a complete Binary Search Tree, write a function that efficiently prints the given array in ascending order. For example, given an array [4, 2, 5, 1, 3], the function should print 1, 2, 3, 4, 5 Solution: Inorder traversal of BST prints it in ascending order. The only trick is to modify recursion termination condition in st
4 min read
Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
Given a binary matrix of size NxN where 1 denotes that the number i can be converted to j, and 0 denotes it cannot be converted to. Also given are two numbers X(<N)and Y(<N), the task is to find the minimum number of steps required to convert the number X to Y. If there is no such way possible, print -1. Examples: Input: {{ 0, 0, 0, 0, 0, 0,
13 min read
Minimum cells traversed to reach corner where every cell represents jumps
Suppose A is at position (0, 0) of a 2-D grid containing 'm' rows and 'n' columns. His aim is to reach the bottom right point of this grid traveling through as minimum number of cells as possible.Each cell of the grid contains a positive integer that defines the number of cells A can jump either in the right or the downward direction when he reache
9 min read
Program to convert a binary number to hexadecimal number
Given a Binary Number, the task is to convert the given binary number to its equivalent hexadecimal number. The input could be very large and may not fit even into an unsigned long long int. Examples: Input: 110001110Output: 18EInput: 1111001010010100001.010110110011011Output: 794A1.5B36 794A1D9B Approach 1:Binary Number: A binary number is a num
13 min read
Check the divisibility of Hexadecimal numbers
Given a string S consisting of a large hexadecimal number, the task is to check its divisibility by a given decimal number M. If divisible then print Yes else print No. Examples: Input: S = "10", M = 4 Output: Yes 10 is 16 in decimal and (16 % 4) = 0 Input: S = "10", M = 5 Output: No Approach 1: In this approach, we first convert the hexadecimal nu
9 min read
Modify array by removing characters from their Hexadecimal representations which are present in a given string
Given an array arr[] of size N and a string S, the task is to modify given array by removing all characters from their hexadecimal representations that are present in S and then replacing the equivalent decimal element back into the array. Examples: Input: arr[] = {74, 91, 31, 122}, S = "1AB"Output: {4, 5, 15, 7}Explanation: 74 -> (4A)16 -> (
10 min read
Program to Convert Hexadecimal Number to Binary
Given a Hexadecimal number as an input, the task is to convert that number to a Binary number.Examples: Input: Hexadecimal = 1AC5 Output: Binary = 0001101011000101 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Equivalent binary value of 5: 0101 Input: Hexadecimal = 5D1F Output:
14 min read
Reverse bytes of a Hexadecimal Number
Given an unsigned integer N. The task is to reverse all bytes of N without using a temporary variable and print the reversed number. Examples: Input: N = 0xaabbccdd Output: 0xddccbbaa Input: N = 0xa912cbd4 Output: 0xd4cb12a9 The naive approach is to extract the appropriate byte is to use mask(&) with shift operators. #define REV(x) ( ((x&0x
4 min read
Largest Even and Odd N-digit numbers in Hexadecimal Number System
Given an integer N, the task is to find the largest even and odd N-digit numbers in Hexadecimal Number System.Examples: Input: N = 1 Output: Even: E Odd: FInput: N = 2 Output: Even: FE Odd: FF Approach: To get the largest number, the digits of the number have to be maximum possible. Since in the hexadecimal number system, the maximum digit is 'F'.
4 min read
Find the count of natural Hexadecimal numbers of size N
Given an integer N, the task is to find the count of natural Hexadecimal numbers with N digits. Examples: Input: N = 1 Output: 15 Input: N = 2 Output: 240 Approach: It can be observed that for the values of N = 1, 2, 3, ..., a series will be formed as 15, 240, 3840, 61440, 983040, 15728640, ... which is a GP series whose common ratio is 16 and a =
2 min read
Largest and Smallest N-digit Hexadecimal Numbers
Given an integer N, the task is to find the smallest and largest N-digit numbers Hexa-Decimal Number System. Examples: Input: N = 4 Output: Largest: FFFF Smallest: 1000 Input: N = 2 Output: Largest: FF Smallest: 10 Approach: The following steps can be followed to complete the required answer: Largest Number: To get the largest number, every digit o
5 min read
How to validate Hexadecimal Color Code using Regular Expression
Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression. The valid hexadecimal color code must satisfy the following conditions. It should start from '#' symbol.It should be followed by the letters from a-f, A-F and/or digits from 0-9.The length of the hexadecimal color code shou
6 min read
Hexadecimal equivalents in Binary Valued Graph
Given a binary valued undirected graph with V vertices and E edges, the task is to find the hexadecimal equivalents of all the connected components of the graph. A binary valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: Chain = 0 1 Hexadecimal equivalent = 1 Chain = 0
15+ min read
Modulus of two Hexadecimal Numbers
Given two hexadecimal numbers N and K, the task is to find N modulo K. Examples: Input: N = 3E8, K = 13 Output: C Explanation: Decimal representation of N( = 3E8) is 1000 Decimal representation of K( = 13) is 19 Decimal representation of (N % K) = 1000 % 19 = 12 ( = C). Therefore, the required output is C. Input: N = 2A3, K = 1A Output: 19 Approach
7 min read
Generate N Random Hexadecimal Numbers
Given a positive integer N, the task is to generate N random hexadecimal integers. Examples: Input: N = 3Output:F9AD0D9E19B24CD01A5E Approach: The given problem can be solved with the help of the rand() function which is used to generate random integers. A character array can be created which stores all the possible characters in the hexadecimal no
5 min read
How to add two Hexadecimal numbers?
Given two numeric Hexadecimal numbers str1 and str2, the task is to add the two hexadecimal numbers. Hexadecimal Number system, often shortened to “hex”, is a number system made up from 16 symbols. it uses 10 symbols from decimal number system which are represented by 0-9 and six extra symbols A - F which represent decimal 10 - 15. Examples: Input:
15+ min read
Program for decimal to hexadecimal conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16. Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A - F.
8 min read
Trending in News
- OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
- How to Merge Cells in Google Sheets: Step by Step Guide
- How to Lock Cells in Google Sheets : Step by Step Guide
- PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
- #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });